Skip to content

Commit

Permalink
Merge pull request #152 from jupiter-project/dev
Browse files Browse the repository at this point in the history
Fix encryption files
  • Loading branch information
joramirezStackit authored Mar 18, 2022
2 parents 16a4a04 + e160ccd commit 2b4447e
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 23 deletions.
2 changes: 1 addition & 1 deletion services/gravityCrypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ class GravityCrypto {
*/
decryptAndParseGCM(data){
const decryptedValue = this.decryptOrPassThroughGCM(data);
return JSON.parse(decryptedValue);
return typeof decryptedValue === 'object' ? decryptedValue : JSON.parse(decryptedValue);
}


Expand Down
4 changes: 2 additions & 2 deletions services/jupiterTransactionMessageService.js
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ class JupiterTransactionMessageService {
logger.warn('???????????????????????????????????????????????\n');
return '';
}
const messageToParse = decryptedMessageContainer.tag.includes(metisConfig.evm)
const messageToParse = decryptedMessageContainer.tag.includes(`.${metisConfig.evm}`)
? crypto.decryptOrNullGCM(decryptedMessageContainer.message)
: crypto.decryptOrNull(decryptedMessageContainer.message);
if (!messageToParse) {
Expand Down Expand Up @@ -382,7 +382,7 @@ class JupiterTransactionMessageService {
// logger.error('what happens if i try to parse a non JSON String?');
// logger.debug(`decryptedMessage.message= ${decryptedMessage.message}`);
// logger.sensitive(`password= ${crypto.decryptionPassword}`);
const messageToParse = messageContainer.tag.includes(metisConfig.evm)
const messageToParse = messageContainer.tag.includes(`.${metisConfig.evm}`)
? crypto.decryptOrPassThroughGCM(messageContainer.message)
: crypto.decryptOrPassThrough(messageContainer.message);

Expand Down
10 changes: 8 additions & 2 deletions services/jupiterTransactionsService.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const {MetisError} = require("../errors/metisError");
const mError = require("../errors/metisError");
const {validator} = require("./validator");
const {GravityCrypto} = require("./gravityCrypto");
const {metisConfig} = require("../config/constants");

class JupiterTransactionsService {

Expand Down Expand Up @@ -129,17 +130,20 @@ class JupiterTransactionsService {
* @param transactionId
* @param sharedKey
* @param isEncrypted
* @param tag
* @returns {Object}
*/
async getReadableMessageContainersBySharedKey(transactionId, sharedKey, isEncrypted = false){
async getReadableMessageContainersBySharedKey(transactionId, sharedKey, tag, isEncrypted = false){
console.log(`\n`)
logger.verbose(`########################################################################`);
logger.verbose(`## getReadableTaggedMessageContainersBySharedKey( transactionId,sharedKey)`);
logger.verbose(`########################################################################\n`);
if(!gu.isNonEmptyString(transactionId)){throw new MetisError('transactionId is invalid')}
if(!gu.isNonEmptyString(sharedKey)){throw new MetisError('sharedKey is invalid')}
if(!gu.isNonEmptyString(tag)){throw new MetisError('tag is invalid')}
logger.verbose(`transactionId= ${transactionId}`);
logger.verbose(`sharedKey= ${sharedKey}`);
logger.verbose(`tag= ${tag}`);

const transaction = await this.jupiterAPIService.getReadableMessageBySharedKey(transactionId, sharedKey);

Expand All @@ -148,7 +152,9 @@ class JupiterTransactionsService {
}

const crypto = new GravityCrypto(process.env.ENCRYPT_ALGORITHM, sharedKey);
return crypto.decryptAndParseOrNull(transaction.decryptedMessage);
return tag.includes(`.${metisConfig.evm}`)
? crypto.decryptAndParseOrNullGCM(transaction.decryptedMessage)
: crypto.decryptAndParseOrNull(transaction.decryptedMessage);
}


Expand Down
15 changes: 12 additions & 3 deletions src/jim/routes/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {storageService} from "../services/storageService";
import {localFileCacheService} from "../services/localFileCacheService";
import {chanService} from "../../../services/chanService";
import {jupiterAPIService} from "../../../services/jupiterAPIService";
import {userConfig} from "../../../config/constants";
import {metisConfig, userConfig} from "../../../config/constants";
import {FeeManager, feeManagerSingleton} from "../../../services/FeeManager";
import {jupiterTransactionsService} from "../../../services/jupiterTransactionsService";
import {GravityCrypto} from "../../../services/gravityCrypto";
Expand Down Expand Up @@ -318,9 +318,18 @@ module.exports = (app, jobs, websocket) => {
if(!messageContainers){
return res.status(StatusCode.ClientErrorNotFound).send({message: 'No image found'});
}
const [fileUuid, transactionId, sharedKey] = messageContainers.attachment.message.split('.').slice(-3);
const messageContainerTag = messageContainers.attachment.message;
let fileUuid = '';
let transactionId = '';
let sharedKey = '';
let tag = '';
if(messageContainerTag.includes(`.${metisConfig.evm}`)){
[fileUuid, transactionId, sharedKey, tag] = messageContainers.attachment.message.split('.').slice(-4);
} else {
[fileUuid, transactionId, sharedKey] = messageContainers.attachment.message.split('.').slice(-3);
}

const fileInfo = await storageService.fetchFileInfoBySharedKey(transactionId, sharedKey, fileUuid);
const fileInfo = await storageService.fetchFileInfoBySharedKey(transactionId, sharedKey, fileUuid, messageContainerTag);
res.setHeader('Content-Type', `${fileInfo.mimeType}`);
res.setHeader('Content-Disposition', `inline; filename="${fileInfo.fileName}"`);
res.sendFile(fileInfo.bufferDataPath);
Expand Down
3 changes: 2 additions & 1 deletion src/jim/services/localFileCacheService.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ class LocalFileCacheService {
if(!gu.isWellFormedUuid(fileUuid)) throw new mError.MetisErrorBadUuid(`fileUuid=${fileUuid}`);
if(!encryptedFileRecord) throw new mError.MetisError(`encryptedFileRecord is empty!`);
const fileRecordPath = this.generateFileRecordPath(fileUuid);
fs.writeFileSync(fileRecordPath, encryptedFileRecord);
const data = typeof encryptedFileRecord === 'string' ? encryptedFileRecord : JSON.stringify(encryptedFileRecord);
fs.writeFileSync(fileRecordPath, data);
}

/**
Expand Down
29 changes: 15 additions & 14 deletions src/jim/services/storageService.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import mError from "../../../errors/metisError";
import {chanService} from "../../../services/chanService";
import {localFileCacheService} from "./localFileCacheService";
import {GravityCrypto} from "../../../services/gravityCrypto";
import {metisConfig} from "../../../config/constants";
const logger = require('../../../utils/logger')(module);
const gu = require('../../../utils/gravityUtils');
const {GravityAccountProperties} = require("../../../gravity/gravityAccountProperties");
Expand Down Expand Up @@ -339,7 +340,7 @@ class StorageService {
logger.info(` GETTING FILE FROM CACHE`);
logger.info(`-__-__-__-__-__-__-__-__-__-__-__-__-__-__-__--\n`);
const encryptedFileRecord = this.fileCacheService.getFileRecord(fileUuid);
fileRecord = ownerAccountProperties.crypto.decryptAndParse(encryptedFileRecord);
fileRecord = ownerAccountProperties.crypto.decryptAndParseGCM(encryptedFileRecord);
} else {
// GETTING FILE FROM BLOCKCHAIN
console.log(`\n`);
Expand All @@ -349,7 +350,7 @@ class StorageService {
const fetchFileFromBlockChainResponse = await this.fetchFileFromBlockChain(ownerAccountProperties,fileUuid);
bufferData = fetchFileFromBlockChainResponse.bufferData;
fileRecord = fetchFileFromBlockChainResponse.fileRecord;
const encryptedFileRecord = ownerAccountProperties.crypto.encryptJson(fileRecord);
const encryptedFileRecord = ownerAccountProperties.crypto.encryptJsonGCM(fileRecord);
this.fileCacheService.sendBufferDataToCache(fileUuid,bufferData);
this.fileCacheService.sendFileRecordToCache(fileUuid,encryptedFileRecord);
}
Expand Down Expand Up @@ -432,11 +433,12 @@ class StorageService {
}


async fetchFileInfoBySharedKey(transactionId, sharedKey, fileUuid){
async fetchFileInfoBySharedKey(transactionId, sharedKey, fileUuid, tag){
logger.verbose(`#### fetchFileInfoBySharedKey(transactionId, sharedKey, fileUuid)`);
if(!gu.isNonEmptyString(transactionId)) throw new mError.MetisErrorBadUuid(`transactionId: ${transactionId}`);
if(!gu.isNonEmptyString(sharedKey)) throw new mError.MetisErrorBadUuid(`transactionId: ${sharedKey}`);
if(!gu.isWellFormedUuid(fileUuid)) throw new mError.MetisErrorBadUuid(`fileUuid: ${fileUuid}`);
if(!tag) throw new mError.MetisErrorBadUuid(`tag: ${tag}`);
let bufferData = null;
let fileRecord = null;
try {
Expand All @@ -448,18 +450,17 @@ class StorageService {
logger.info(` GETTING FILE FROM CACHE`);
logger.info(`-__-__-__-__-__-__-__-__-__-__-__-__-__-__-__--\n`);
const encryptedFileRecord = this.fileCacheService.getFileRecord(fileUuid);
fileRecord = crypto.decryptAndParse(encryptedFileRecord);
fileRecord = tag.includes(`.${metisConfig.evm}`) ? crypto.decryptAndParseGCM(encryptedFileRecord) : crypto.decryptAndParse(encryptedFileRecord);
} else {
// GETTING FILE FROM BLOCKCHAIN
console.log(`\n`);
logger.info(`-__-__-__-__-__-__-__-__-__-__-__-__-__-__-__--`);
logger.info(` GETTING FILE FROM BLOCKCHAIN`);
logger.info(`-__-__-__-__-__-__-__-__-__-__-__-__-__-__-__--\n`);
const fetchFileFromBlockChainResponse = await this.fetchFileFromBlockChainBySharedKey(transactionId, sharedKey);
const fetchFileFromBlockChainResponse = await this.fetchFileFromBlockChainBySharedKey(transactionId, sharedKey, tag);
bufferData = fetchFileFromBlockChainResponse.bufferData;
fileRecord = fetchFileFromBlockChainResponse.fileRecord;

const encryptedFileRecord = crypto.encryptJson(fileRecord);
const encryptedFileRecord = tag.includes(`.${metisConfig.evm}`) ? crypto.decryptAndParseGCM(fileRecord) : crypto.decryptAndParse(fileRecord);
this.fileCacheService.sendBufferDataToCache(fileUuid,bufferData);
this.fileCacheService.sendFileRecordToCache(fileUuid,encryptedFileRecord);
}
Expand Down Expand Up @@ -490,12 +491,12 @@ class StorageService {
* @param transactionId
* @param sharedKey
*/
async fetchFileFromBlockChainBySharedKey(transactionId, sharedKey){
async fetchFileFromBlockChainBySharedKey(transactionId, sharedKey, tag){
logger.verbose(`#### fetchFileFromBlockChainBySharedKey()`);
if(!gu.isNonEmptyString(transactionId)) throw new mError.MetisErrorBadUuid(`transactionId is missing`);
if(!gu.isNonEmptyString(sharedKey)) throw new mError.MetisErrorBadUuid(`sharedKey is missing`);
try {
const fileRecord = await jupiterTransactionsService.getReadableMessageContainersBySharedKey(transactionId, sharedKey);
const fileRecord = await jupiterTransactionsService.getReadableMessageContainersBySharedKey(transactionId, sharedKey, tag);

const chunkTransactionIds = fileRecord.chunkTransactionIds;
// GET ALL THE CHUNKS
Expand All @@ -504,7 +505,7 @@ class StorageService {
logger.info(` GET ALL THE CHUNKS`);
logger.info(`-__-__-__-__-__-__-__-__-__-__-__-__-__-__-__--\n`);
const readableMessageContainer$ = chunkTransactionIds.map(chunkTransactionId =>
jupiterTransactionsService.getReadableMessageContainersBySharedKey(chunkTransactionId.transactionId, chunkTransactionId.sharedKey)
jupiterTransactionsService.getReadableMessageContainersBySharedKey(chunkTransactionId.transactionId, chunkTransactionId.sharedKey, tag)
);
const chunkContainers = await Promise.all(readableMessageContainer$);
if(chunkContainers.length < 1) throw new mError.MetisErrorNoBinaryFileFound(`No Chunks found`);
Expand Down Expand Up @@ -632,7 +633,7 @@ class StorageService {

const _fileRecord = (fileCat === FileCategory.PublicProfile || fileCat === FileCategory.ChannelProfile) ?
JSON.stringify(fileRecord):
toAccountProperties.crypto.encryptJson(fileRecord)
toAccountProperties.crypto.encryptJsonGCM(fileRecord)
if(!this.fileCacheService.bufferDataExists(fileUuid)){
this.fileCacheService.sendBufferDataToCache(fileUuid,bufferData);
}
Expand All @@ -651,20 +652,20 @@ class StorageService {

if(fileCat === FileCategory.PublicProfile || fileCat === FileCategory.ChannelProfile){
const crypto = new GravityCrypto(process.env.ENCRYPT_ALGORITHM, xSharedKey);
const encryptedFileRecord = crypto.encryptJson(fileRecord);
const encryptedFileRecord = crypto.encryptJsonGCM(fileRecord);
this.fileCacheService.sendFileRecordToCache(fileUuid, encryptedFileRecord);
const sendMessageResponsePublicFileSharedKey = await this.jupiterTransactionsService.messageService.sendTaggedAndEncipheredMetisMessage(
toAccountProperties.passphrase,
toAccountProperties.address,
_fileRecord,
`${transactionTags.jimServerTags.binaryFilePublicProfileSharedKey}.${fileUuid}.${xInfo.transactionId}.${xSharedKey}`,
`${transactionTags.jimServerTags.binaryFilePublicProfileSharedKey}.${fileUuid}.${xInfo.transactionId}.${xSharedKey}.${metisConfig.evm}`,
FeeManager.feeTypes.metisMessage,
toAccountProperties.publicKey
);
return {fileRecord: encryptedFileRecord, sharedKey: xSharedKey}
}

const encryptedFileRecord = toAccountProperties.crypto.encryptJson(fileRecord);
const encryptedFileRecord = toAccountProperties.crypto.encryptJsonGCM(fileRecord);
this.fileCacheService.sendFileRecordToCache(fileUuid, encryptedFileRecord);

return {fileRecord: _fileRecord}
Expand Down

0 comments on commit 2b4447e

Please sign in to comment.