@ethernity-cloud/sdk-js 1.5.5 → 1.5.9

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.
@@ -1,211 +1,211 @@
1
- const fs = require("fs");
2
- const elliptic = require('elliptic');
3
- const crypto = require('crypto');
4
- const rs = require('jsrsasign');
5
- const ECKey = require('ec-key');
6
- const curve = new elliptic.ec('p384');
7
- const ascii85 = require('ascii85');
8
- const ethSigUtil = require('@metamask/eth-sig-util');
9
- const {createHash} = require('crypto');
10
-
11
- function sha256(content) {
12
- return createHash('sha256').update(content).digest('hex');
13
- }
14
-
15
- function fileChecksum(file) {
16
- const fileContent = fs.readFileSync(file, 'utf8');
17
- return sha256(fileContent);
18
- }
19
-
20
- async function fileChecksumFromSwiftStream(swiftStreamClient, bucketName, fileName) {
21
- const fileContent = await swiftStreamClient.getFileContent(bucketName, fileName);
22
- //console.log(fileContent);
23
- return sha256(fileContent);
24
- }
25
-
26
- const getPEMFromPublicFile = (publicKeyPath) => {
27
- const publicKey = fs.readFileSync(publicKeyPath, 'utf8');
28
- return crypto.createPublicKey(publicKey).export({type: 'spki', format: 'pem'});
29
- }
30
-
31
- const getPEMFromPublic = (publicKey) => {
32
- return crypto.createPublicKey(publicKey).export({type: 'spki', format: 'pem'});
33
- }
34
-
35
- const loadCertificate = (certificate) => {
36
- //console.log(certificate)
37
- const publicKeyPEM = getPEMFromPublic(certificate);
38
- const key = new ECKey(publicKeyPEM, 'pem');
39
- //console.log(key);
40
- return key;
41
- }
42
-
43
- // Accepts EITHER a path to a PEM file or the PEM text itself.
44
- //
45
- // mainnet keeps passing a path: CAS injects the key into key_file after
46
- // attestation, and that flow is unchanged. On testnet the enclave self-derives
47
- // its key and now holds it only in memory (never writes it), so it passes the
48
- // PEM straight through -- nothing about the key ever reaches the filesystem.
49
- // Detection is on the PEM header, not on file existence, so a path that does
50
- // not exist still fails loudly instead of being mistaken for key material.
51
- function getPrivatePointFromPrivateKey(privateKeyOrFile) {
52
- const value = String(privateKeyOrFile || '');
53
- const privateKey = value.includes('-----BEGIN')
54
- ? value
55
- : fs.readFileSync(value, 'utf8');
56
- let privateKeyHex = rs.KEYUTIL.getKey(privateKey).prvKeyHex;
57
- const privateKeyObject = curve.keyFromPrivate(privateKeyHex, 'hex');
58
- return privateKeyObject.getPrivate();
59
- }
60
-
61
- const generatePublicKey = (x, y) => {
62
- const pub = {x: x, y};
63
- return curve.keyFromPublic(pub, 'hex');
64
- }
65
-
66
- function getPublicPointFromCoords(x, y) {
67
- const publicKey = generatePublicKey(x, y);
68
- return publicKey.getPublic();
69
- }
70
-
71
- function ecc_point_to_256_bit_key(point) {
72
- const value = point.getX().toString() + point.getY().toString();
73
- const hash = crypto.createHash('sha256');
74
- hash.update(value);
75
- return hash.digest();
76
- }
77
-
78
- function encryptedDataToBase64Json(encryptedMsg) {
79
- const key = curve.keyFromPublic(encryptedMsg.cipherTextPublicKey, 'hex');
80
- const jsonObj = {
81
- ciphertext: encryptedMsg.ciphertext.toString('hex'),
82
- nonce: encryptedMsg.nonce.toString('hex'),
83
- authTag: encryptedMsg.authTag.toString('hex'),
84
- x: key.getPublic().getX(),
85
- y: key.getPublic().getY()
86
- };
87
- const jsonString = JSON.stringify(jsonObj);
88
- const binaryData = Buffer.from(jsonString, 'utf8');
89
- return binaryData.toString('base64');
90
- }
91
-
92
- function encryptedDataFromBase64Json(base64Data) {
93
- // decode the base64-encoded string back to a JSON string
94
- const decodedJsonData = Buffer.from(base64Data, 'base64').toString('utf8');
95
- return JSON.parse(decodedJsonData);
96
- }
97
-
98
-
99
- function encrypt(certificate, message) {
100
- const key = loadCertificate(certificate);
101
- return encrypt_ecc(message, generatePublicKey(key.x, key.y));
102
- }
103
-
104
- function encrypt_ecc(msg, publicKey) {
105
- const cipherTextPrivateKey = crypto.randomBytes(32);
106
- const sharedEccKey = publicKey.getPublic().mul(cipherTextPrivateKey);
107
- const secretKey = ecc_point_to_256_bit_key(sharedEccKey);
108
- const iv = crypto.randomBytes(16);
109
- const cipher = crypto.createCipheriv('aes-256-gcm', secretKey, iv);
110
- let encrypted = cipher.update(msg, 'utf8', 'hex');
111
- encrypted += cipher.final('hex');
112
- const cipherTextPublicKey = curve.g.mul(cipherTextPrivateKey);
113
- return {
114
- ciphertext: encrypted,
115
- secretKey: secretKey,
116
- nonce: iv,
117
- authTag: cipher.getAuthTag().toString("hex"),
118
- cipherTextPublicKey: cipherTextPublicKey.encode('hex')
119
- };
120
- }
121
-
122
- function decrypt(privateKeyFile, encryptedMsg) {
123
- //console.log(privateKeyFile);
124
- const privatePoint = getPrivatePointFromPrivateKey(privateKeyFile);
125
- return decrypt_ecc(encryptedMsg, privatePoint);
126
- }
127
-
128
- function decrypt_ecc(encryptedMsg, privatePoint) {
129
- try {
130
- const {ciphertext, nonce, authTag, x, y} = encryptedMsg;
131
- const publicPoint = getPublicPointFromCoords(`${x}`, `${y}`);
132
- const sharedEccKey = publicPoint.mul(privatePoint);
133
- const secretKey = ecc_point_to_256_bit_key(sharedEccKey);
134
-
135
- const decipher = crypto.createDecipheriv('aes-256-gcm', secretKey, Buffer.from(nonce, 'hex'));
136
- decipher.setAuthTag(Buffer.from(authTag, 'hex'));
137
- let decrypted = decipher.update(ciphertext, 'hex', 'utf8');
138
- decrypted += decipher.final('utf8');
139
- return decrypted;
140
- } catch (e) {
141
- console.log(`Error while decrypting ECC:`, e.message);
142
- return false;
143
- }
144
- }
145
-
146
- function hexToBytes(hexStr) {
147
- if (hexStr.startsWith("0x")) {
148
- hexStr = hexStr.slice(2);
149
- }
150
- return Buffer.from(hexStr, "hex");
151
- }
152
-
153
- function encryptWithPublicKey(publicKey, data) {
154
- // Returned object contains 4 properties: version, ephemPublicKey, nonce, ciphertext
155
- // Each contains data encoded using base64, version is always the same string
156
- const enc = ethSigUtil.encrypt({
157
- publicKey: hexToBytes(publicKey).toString('base64'),
158
- data: ascii85.encode(Buffer.from(data)).toString(),
159
- version: 'x25519-xsalsa20-poly1305',
160
- });
161
-
162
- // We want to store the data in smart contract, therefore we concatenate them
163
- // into single Buffer
164
- const buf = Buffer.concat([
165
- Buffer.from(enc.ephemPublicKey, 'base64'),
166
- Buffer.from(enc.nonce, 'base64'),
167
- Buffer.from(enc.ciphertext, 'base64'),
168
- ]);
169
-
170
- // In smart contract we are using `bytes[112]` variable (fixed size byte array)
171
- // you might need to use `bytes` type for dynamic sized array
172
- // We are also using ethers.js which requires type `number[]` when passing data
173
- // for argument of type `bytes` to the smart contract function
174
- // Next line just converts the buffer to `number[]` required by contract function
175
- // THIS LINE IS USED IN OUR ORIGINAL CODE:
176
- // return buf.toJSON().data;
177
-
178
- // Return just the Buffer to make the function directly compatible with decryptData function
179
- return buf;
180
- }
181
-
182
- // (async () => {
183
- // try {
184
- // const message = 'testabc1';
185
- // console.log('initial message:', message);
186
- // const publicKeyPEM = getPEMFromPublic('./app/cert1-ca1-clean.crt');
187
- // const ECKey = require('ec-key');
188
- // const key = new ECKey(publicKeyPEM, 'pem');
189
- // const encrypted_message = encrypt(key.x, key.y, message);
190
- // console.log(encrypted_message);
191
- // console.log(encryptedDataToBase64Json(encrypted_message));
192
- // //
193
- // // const encrypted_message = 'eyJjaXBoZXJ0ZXh0IjoiZTYzZTcyNDY0MWY4YWRmN2QyNjNmMTI0ZGYxZTdlYzZmNGM5NGU1NCIsIm5vbmNlIjoiYmE0YWU5YjMyOWFhZWRiM2ViZTM5MGU4YTY3YWFiNmMiLCJhdXRoVGFnIjoiOGU2NmI4NTVmNTE3N2E0NzZlMjkwNTE3Y2Q2ZDE3ZmUiLCJ4IjoiN2E1MjhhNGI5YzAzODM4Mjc0ZmFiYzVlM2RiOWQ2ZWFiNzBiZTFiMDA3YWJiOTcyYzI0YmFhNGE1ZmI4OGJjNTVmNDVlNGNkMjZjY2NhNTFhOTk3OGZkNDRhZmE1YjQ0IiwieSI6IjE5M2NjMWYwMzVmOGMxZjEzNGU4MTEzOGIyOTRiODBiZWQyYjkyMzdkZmIyOTMyOGRjOTg1MzlmMjhkNjIzMTJiYTQ2OTU2NDFkYjIyNjk0ZWUyNGFjZjQ4MjBiZDlhMSJ9';
194
- // // const messageDecrypted = decrypt('./app/cert1-ca1-clean.key', encryptedDataToBase64Json(encrypted_message));
195
- // // console.log('decrypted message:', messageDecrypted);
196
- // } catch (e) {
197
- // console.log(e);
198
- // }
199
- //
200
- // })();
201
-
202
- module.exports = {
203
- encryptedDataFromBase64Json,
204
- encryptedDataToBase64Json,
205
- encryptWithPublicKey,
206
- decrypt,
207
- encrypt,
208
- sha256,
209
- fileChecksum,
210
- fileChecksumFromSwiftStream
211
- };
1
+ const fs = require("fs");
2
+ const elliptic = require('elliptic');
3
+ const crypto = require('crypto');
4
+ const rs = require('jsrsasign');
5
+ const ECKey = require('ec-key');
6
+ const curve = new elliptic.ec('p384');
7
+ const ascii85 = require('ascii85');
8
+ const ethSigUtil = require('@metamask/eth-sig-util');
9
+ const {createHash} = require('crypto');
10
+
11
+ function sha256(content) {
12
+ return createHash('sha256').update(content).digest('hex');
13
+ }
14
+
15
+ function fileChecksum(file) {
16
+ const fileContent = fs.readFileSync(file, 'utf8');
17
+ return sha256(fileContent);
18
+ }
19
+
20
+ async function fileChecksumFromSwiftStream(swiftStreamClient, bucketName, fileName) {
21
+ const fileContent = await swiftStreamClient.getFileContent(bucketName, fileName);
22
+ //console.log(fileContent);
23
+ return sha256(fileContent);
24
+ }
25
+
26
+ const getPEMFromPublicFile = (publicKeyPath) => {
27
+ const publicKey = fs.readFileSync(publicKeyPath, 'utf8');
28
+ return crypto.createPublicKey(publicKey).export({type: 'spki', format: 'pem'});
29
+ }
30
+
31
+ const getPEMFromPublic = (publicKey) => {
32
+ return crypto.createPublicKey(publicKey).export({type: 'spki', format: 'pem'});
33
+ }
34
+
35
+ const loadCertificate = (certificate) => {
36
+ //console.log(certificate)
37
+ const publicKeyPEM = getPEMFromPublic(certificate);
38
+ const key = new ECKey(publicKeyPEM, 'pem');
39
+ //console.log(key);
40
+ return key;
41
+ }
42
+
43
+ // Accepts EITHER a path to a PEM file or the PEM text itself.
44
+ //
45
+ // mainnet keeps passing a path: CAS injects the key into key_file after
46
+ // attestation, and that flow is unchanged. On testnet the enclave self-derives
47
+ // its key and now holds it only in memory (never writes it), so it passes the
48
+ // PEM straight through -- nothing about the key ever reaches the filesystem.
49
+ // Detection is on the PEM header, not on file existence, so a path that does
50
+ // not exist still fails loudly instead of being mistaken for key material.
51
+ function getPrivatePointFromPrivateKey(privateKeyOrFile) {
52
+ const value = String(privateKeyOrFile || '');
53
+ const privateKey = value.includes('-----BEGIN')
54
+ ? value
55
+ : fs.readFileSync(value, 'utf8');
56
+ let privateKeyHex = rs.KEYUTIL.getKey(privateKey).prvKeyHex;
57
+ const privateKeyObject = curve.keyFromPrivate(privateKeyHex, 'hex');
58
+ return privateKeyObject.getPrivate();
59
+ }
60
+
61
+ const generatePublicKey = (x, y) => {
62
+ const pub = {x: x, y};
63
+ return curve.keyFromPublic(pub, 'hex');
64
+ }
65
+
66
+ function getPublicPointFromCoords(x, y) {
67
+ const publicKey = generatePublicKey(x, y);
68
+ return publicKey.getPublic();
69
+ }
70
+
71
+ function ecc_point_to_256_bit_key(point) {
72
+ const value = point.getX().toString() + point.getY().toString();
73
+ const hash = crypto.createHash('sha256');
74
+ hash.update(value);
75
+ return hash.digest();
76
+ }
77
+
78
+ function encryptedDataToBase64Json(encryptedMsg) {
79
+ const key = curve.keyFromPublic(encryptedMsg.cipherTextPublicKey, 'hex');
80
+ const jsonObj = {
81
+ ciphertext: encryptedMsg.ciphertext.toString('hex'),
82
+ nonce: encryptedMsg.nonce.toString('hex'),
83
+ authTag: encryptedMsg.authTag.toString('hex'),
84
+ x: key.getPublic().getX(),
85
+ y: key.getPublic().getY()
86
+ };
87
+ const jsonString = JSON.stringify(jsonObj);
88
+ const binaryData = Buffer.from(jsonString, 'utf8');
89
+ return binaryData.toString('base64');
90
+ }
91
+
92
+ function encryptedDataFromBase64Json(base64Data) {
93
+ // decode the base64-encoded string back to a JSON string
94
+ const decodedJsonData = Buffer.from(base64Data, 'base64').toString('utf8');
95
+ return JSON.parse(decodedJsonData);
96
+ }
97
+
98
+
99
+ function encrypt(certificate, message) {
100
+ const key = loadCertificate(certificate);
101
+ return encrypt_ecc(message, generatePublicKey(key.x, key.y));
102
+ }
103
+
104
+ function encrypt_ecc(msg, publicKey) {
105
+ const cipherTextPrivateKey = crypto.randomBytes(32);
106
+ const sharedEccKey = publicKey.getPublic().mul(cipherTextPrivateKey);
107
+ const secretKey = ecc_point_to_256_bit_key(sharedEccKey);
108
+ const iv = crypto.randomBytes(16);
109
+ const cipher = crypto.createCipheriv('aes-256-gcm', secretKey, iv);
110
+ let encrypted = cipher.update(msg, 'utf8', 'hex');
111
+ encrypted += cipher.final('hex');
112
+ const cipherTextPublicKey = curve.g.mul(cipherTextPrivateKey);
113
+ return {
114
+ ciphertext: encrypted,
115
+ secretKey: secretKey,
116
+ nonce: iv,
117
+ authTag: cipher.getAuthTag().toString("hex"),
118
+ cipherTextPublicKey: cipherTextPublicKey.encode('hex')
119
+ };
120
+ }
121
+
122
+ function decrypt(privateKeyFile, encryptedMsg) {
123
+ //console.log(privateKeyFile);
124
+ const privatePoint = getPrivatePointFromPrivateKey(privateKeyFile);
125
+ return decrypt_ecc(encryptedMsg, privatePoint);
126
+ }
127
+
128
+ function decrypt_ecc(encryptedMsg, privatePoint) {
129
+ try {
130
+ const {ciphertext, nonce, authTag, x, y} = encryptedMsg;
131
+ const publicPoint = getPublicPointFromCoords(`${x}`, `${y}`);
132
+ const sharedEccKey = publicPoint.mul(privatePoint);
133
+ const secretKey = ecc_point_to_256_bit_key(sharedEccKey);
134
+
135
+ const decipher = crypto.createDecipheriv('aes-256-gcm', secretKey, Buffer.from(nonce, 'hex'));
136
+ decipher.setAuthTag(Buffer.from(authTag, 'hex'));
137
+ let decrypted = decipher.update(ciphertext, 'hex', 'utf8');
138
+ decrypted += decipher.final('utf8');
139
+ return decrypted;
140
+ } catch (e) {
141
+ console.log(`Error while decrypting ECC:`, e.message);
142
+ return false;
143
+ }
144
+ }
145
+
146
+ function hexToBytes(hexStr) {
147
+ if (hexStr.startsWith("0x")) {
148
+ hexStr = hexStr.slice(2);
149
+ }
150
+ return Buffer.from(hexStr, "hex");
151
+ }
152
+
153
+ function encryptWithPublicKey(publicKey, data) {
154
+ // Returned object contains 4 properties: version, ephemPublicKey, nonce, ciphertext
155
+ // Each contains data encoded using base64, version is always the same string
156
+ const enc = ethSigUtil.encrypt({
157
+ publicKey: hexToBytes(publicKey).toString('base64'),
158
+ data: ascii85.encode(Buffer.from(data)).toString(),
159
+ version: 'x25519-xsalsa20-poly1305',
160
+ });
161
+
162
+ // We want to store the data in smart contract, therefore we concatenate them
163
+ // into single Buffer
164
+ const buf = Buffer.concat([
165
+ Buffer.from(enc.ephemPublicKey, 'base64'),
166
+ Buffer.from(enc.nonce, 'base64'),
167
+ Buffer.from(enc.ciphertext, 'base64'),
168
+ ]);
169
+
170
+ // In smart contract we are using `bytes[112]` variable (fixed size byte array)
171
+ // you might need to use `bytes` type for dynamic sized array
172
+ // We are also using ethers.js which requires type `number[]` when passing data
173
+ // for argument of type `bytes` to the smart contract function
174
+ // Next line just converts the buffer to `number[]` required by contract function
175
+ // THIS LINE IS USED IN OUR ORIGINAL CODE:
176
+ // return buf.toJSON().data;
177
+
178
+ // Return just the Buffer to make the function directly compatible with decryptData function
179
+ return buf;
180
+ }
181
+
182
+ // (async () => {
183
+ // try {
184
+ // const message = 'testabc1';
185
+ // console.log('initial message:', message);
186
+ // const publicKeyPEM = getPEMFromPublic('./app/cert1-ca1-clean.crt');
187
+ // const ECKey = require('ec-key');
188
+ // const key = new ECKey(publicKeyPEM, 'pem');
189
+ // const encrypted_message = encrypt(key.x, key.y, message);
190
+ // console.log(encrypted_message);
191
+ // console.log(encryptedDataToBase64Json(encrypted_message));
192
+ // //
193
+ // // const encrypted_message = 'eyJjaXBoZXJ0ZXh0IjoiZTYzZTcyNDY0MWY4YWRmN2QyNjNmMTI0ZGYxZTdlYzZmNGM5NGU1NCIsIm5vbmNlIjoiYmE0YWU5YjMyOWFhZWRiM2ViZTM5MGU4YTY3YWFiNmMiLCJhdXRoVGFnIjoiOGU2NmI4NTVmNTE3N2E0NzZlMjkwNTE3Y2Q2ZDE3ZmUiLCJ4IjoiN2E1MjhhNGI5YzAzODM4Mjc0ZmFiYzVlM2RiOWQ2ZWFiNzBiZTFiMDA3YWJiOTcyYzI0YmFhNGE1ZmI4OGJjNTVmNDVlNGNkMjZjY2NhNTFhOTk3OGZkNDRhZmE1YjQ0IiwieSI6IjE5M2NjMWYwMzVmOGMxZjEzNGU4MTEzOGIyOTRiODBiZWQyYjkyMzdkZmIyOTMyOGRjOTg1MzlmMjhkNjIzMTJiYTQ2OTU2NDFkYjIyNjk0ZWUyNGFjZjQ4MjBiZDlhMSJ9';
194
+ // // const messageDecrypted = decrypt('./app/cert1-ca1-clean.key', encryptedDataToBase64Json(encrypted_message));
195
+ // // console.log('decrypted message:', messageDecrypted);
196
+ // } catch (e) {
197
+ // console.log(e);
198
+ // }
199
+ //
200
+ // })();
201
+
202
+ module.exports = {
203
+ encryptedDataFromBase64Json,
204
+ encryptedDataToBase64Json,
205
+ encryptWithPublicKey,
206
+ decrypt,
207
+ encrypt,
208
+ sha256,
209
+ fileChecksum,
210
+ fileChecksumFromSwiftStream
211
+ };
@@ -142,12 +142,23 @@ function executeTask(payload, input) {
142
142
  ' image dependencies, or a bad require() inside backend.js.'
143
143
  ];
144
144
  }
145
- return exec(payload, input, {
145
+ const scope = {
146
146
  '___etny_result___': ___etny_result___, // legacy alias (no ESR)
147
147
  'ecldResult': ecldResult, // the result API
148
148
  'esrFetch': esrFetch, // standard state-fetch task
149
149
  ...backendFunctions,
150
- });
150
+ };
151
+ // State ownership / ACL API (present only in ESR-enabled builds). Enforced
152
+ // inside ecld_state against the trustedzone-attested caller.
153
+ try {
154
+ // eslint-disable-next-line global-require
155
+ const ecldState = require('./ecld_state');
156
+ for (const name of ['taskCaller', 'esrGrant', 'esrRevoke',
157
+ 'esrSetPublicRead', 'esrTransfer', 'esrOwner', 'esrAcl']) {
158
+ if (!(name in scope)) scope[name] = ecldState[name];
159
+ }
160
+ } catch (e) { /* non-ESR build */ }
161
+ return exec(payload, input, scope);
151
162
  }
152
163
 
153
164
  function exec(payload, input, globals = null) {