diff --git a/src/index.ts b/src/index.ts index 30120a1..2fbab88 100755 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,3 @@ export { default as Services } from './services/service'; export { default as Database } from './services/database.service'; export { MessageType } from './models/process.model'; -export type { ProfileData, ProfileMessage } from './models/process.model'; diff --git a/src/router.ts b/src/router.ts index 7ac2259..e984abe 100755 --- a/src/router.ts +++ b/src/router.ts @@ -8,7 +8,7 @@ import { cleanSubscriptions } from './utils/subscription.utils'; import { LoginComponent } from './pages/home/home-component'; import { prepareAndSendPairingTx } from './utils/sp-address.utils'; import ModalService from './services/modal.service'; -import { MessageType, ProfileData, FolderData, LinkAcceptedMessage } from './models/process.model'; +import { MessageType } from './models/process.model'; const routes: { [key: string]: string } = { home: '/src/pages/home/home.html', @@ -216,7 +216,7 @@ export async function registerAllListeners() { try { const tokens = await tokenService.generateSessionToken(event.origin); - const acceptedMsg: LinkAcceptedMessage = { + const acceptedMsg = { type: MessageType.LINK_ACCEPTED, accessToken: tokens.accessToken, refreshToken: tokens.refreshToken @@ -231,46 +231,6 @@ export async function registerAllListeners() { } } - const handleAddProfile = async (event: MessageEvent) => { - if (event.data.type !== MessageType.CREATE_PROFILE) { - return; - } - - if (!services.isPaired()) { - const errorMsg = 'Device not paired'; - errorResponse(errorMsg, event.origin); - return; - } - - try { - const { profileData, accessToken } = event.data; - - if (!accessToken || await !tokenService.validateToken(accessToken, event.origin)) { - throw new Error('Invalid or expired session token'); - } - - // Create profile - const { processId, process } = await services.createAndSendProfileTx(profileData); - - const res = { - processId, - process, - profileData, - }; - - window.parent.postMessage( - { - type: MessageType.PROFILE_CREATED, - profileCreated: res, - }, - event.origin - ); - } catch (e) { - const errorMsg = `Failed to create profile: ${e}`; - errorResponse(errorMsg, event.origin); - } - } - const handleGetMyProcesses = async (event: MessageEvent) => { if (event.data.type !== MessageType.GET_MY_PROCESSES) { return; @@ -309,8 +269,22 @@ export async function registerAllListeners() { return; } + // const tokenService = await TokenService.getInstance(); + + // if (!services.isPaired()) { + // const errorMsg = 'Device not paired'; + // errorResponse(errorMsg, event.origin); + // return; + // } try { + // const { profileData, accessToken } = event.data; + + // // Validate the session token + // if (!accessToken || !tokenService.validateToken(accessToken, event.origin)) { + // throw new Error('Invalid or expired session token'); + // } + const processes = await services.getProcesses(); window.parent.postMessage( @@ -326,45 +300,6 @@ export async function registerAllListeners() { } } - const handleAddFolder = async (event: MessageEvent) => { - if (event.data.type !== MessageType.CREATE_FOLDER) { - return; - } - - if (!services.isPaired()) { - const errorMsg = 'Device not paired'; - errorResponse(errorMsg, event.origin); - return; - } - - try { - const { folderData, accessToken } = event.data; - - if (!accessToken || await !tokenService.validateToken(accessToken, event.origin)) { - throw new Error('Invalid or expired session token'); - } - - const { processId, process } = await services.createAndSendFolderTx(folderData); - - const res = { - processId, - process, - folderData, - }; - - window.parent.postMessage( - { - type: MessageType.FOLDER_CREATED, - folderCreated: res, - }, - event.origin - ); - } catch (e) { - const errorMsg = `Failed to create folder: ${e}`; - errorResponse(errorMsg, event.origin); - } - } - /// We got a state for some process and return as many clear attributes as we can const handleDecryptState = async (event: MessageEvent) => { if (event.data.type !== MessageType.RETRIEVE_DATA) { @@ -626,10 +561,8 @@ export async function registerAllListeners() { // Remove before adding to be sure there's no duplicate window.removeEventListener('message', handleRequestLink); - window.removeEventListener('message', handleAddProfile); window.removeEventListener('message', handleGetProcesses); window.removeEventListener('message', handleGetMyProcesses); - window.removeEventListener('message', handleAddFolder); window.removeEventListener('message', handleDecryptState); window.removeEventListener('message', handleValidateToken); window.removeEventListener('message', handleRenewToken); @@ -639,10 +572,8 @@ export async function registerAllListeners() { window.removeEventListener('message', handleNotifyUpdate); window.addEventListener('message', handleRequestLink); - window.addEventListener('message', handleAddProfile); window.addEventListener('message', handleGetProcesses); window.addEventListener('message', handleGetMyProcesses); - window.addEventListener('message', handleAddFolder); window.addEventListener('message', handleDecryptState); window.addEventListener('message', handleValidateToken); window.addEventListener('message', handleRenewToken); diff --git a/src/services/service.ts b/src/services/service.ts index 50e5bab..5cdcdc4 100755 --- a/src/services/service.ts +++ b/src/services/service.ts @@ -1,7 +1,5 @@ -// import { WebSocketClient } from '../websockets'; import { INotification } from '~/models/notification.model'; import { IProcess } from '~/models/process.model'; -// import Database from './database'; import { initWebsocket, sendMessage } from '../websockets'; import { ApiReturn, Device, HandshakeMessage, Member, OutPointProcessMap, Process, ProcessState, RoleDefinition, SecretsStore, UserDiff } from '../../pkg/sdk_client'; import ModalService from './modal.service'; @@ -372,376 +370,6 @@ export default class Services { return(result); } - public async createDmProcess( - otherMember: string[], - ): Promise { - if (otherMember.length === 0) { - throw new Error('Can\'t open dm with empty user'); - } - try { - console.log('🚀 Début createDmProcess'); - console.log('👥 Other Member:', otherMember); - - if (!this.isPaired()) { - throw new Error('Device not paired'); - } - - const myAddresses = await this.getMemberFromDevice(); - console.log('🔑 Mes adresses:', myAddresses); - - if (!myAddresses) { - throw new Error('No paired member found'); - } - - const roles = { - demiurge: { - members: [ - { sp_addresses: myAddresses }, - ], - validation_rules: [ - { - quorum: 0.01, - fields: ['message', 'description', 'roles'], - min_sig_member: 0.01, - }, - ], - storages: [STORAGEURL] - }, - dm: { - members: [ - { sp_addresses: myAddresses }, - { sp_addresses: otherMember } - ], - validation_rules: [ - { - quorum: 0.01, - fields: ['message', 'description'], - min_sig_member: 0.01, - }, - ], - storages: [STORAGEURL] - } - } - - const dmTemplate = { - description: 'dm', - message: '', - }; - - console.log('📋 Template final:', JSON.stringify(dmTemplate, null, 2)); - - const relayAddress = this.getAllRelays()[0]['spAddress']; - const feeRate = 1; - const publicData = {}; - - await this.checkConnections ([{ sp_addresses: otherMember }]); - - const result = this.sdkClient.create_new_process ( - dmTemplate, - roles, - publicData, - relayAddress, - feeRate - ); - - return result; - - } catch (e) { - console.error('❌ Erreur:', e); - throw e; - } - } - - public async createNotaryProcess(notaryTokens: string[] | null): Promise { - const notaryProcess = await this.lookForNotaryProcess(); - if (notaryProcess) { - console.log('NOTARY PROCESS:', notaryProcess); - throw new Error('There is already a notary process'); - } - const myProcessId: string = this.getPairingProcessId(); - const roles: Record = { - notary: { - members: [myProcessId], - validation_rules: [ - { - quorum: 0, - fields: ['roles', 'idNotTokens'], - min_sig_member: 0, - }, - ], - storages: [STORAGEURL] - }, - }; - - const pairingTemplate = { - description: 'notary', - }; - const publicData = { - idNotTokens: notaryTokens, - } - const relayAddress = this.getAllRelays()[0]['spAddress']; - const feeRate = 1; - - await this.getTokensFromFaucet(); - - try { - return this.sdkClient.create_new_process( - pairingTemplate, - roles, - publicData, - relayAddress, - feeRate, - this.getAllMembers() - ); - } catch (e) { - throw new Error(`Creating process failed:, ${e}`); - } - } - - public async createProfileProcess(userData: any): Promise { - const myProcessId: string = this.getPairingProcessId(); - if (!myProcessId) { - throw new Error('Missing pairing id'); - } - - const validator = userData['validator']; - - delete userData.validator; // We don't want that in the final pcd - - const privateData = { - description: 'profile', - ...userData, - }; - const publicData = { - identityCertified: false, - }; - const ownerRoleFields: string[] = [...Object.keys(privateData), 'roles']; - const validatorRoleFields: string[] = [...Object.keys(publicData)]; - const roles: Record = { - demiurge: { - members: [myProcessId], - validation_rules: [], - storages: [STORAGEURL] - }, - owner: { - members: [myProcessId], - validation_rules: [ - { - quorum: 0.01, - fields: ownerRoleFields, - min_sig_member: 0.01, - }, - ], - storages: [STORAGEURL] - }, - idCertificator: { - members: [validator], - validation_rules: [ - { - quorum: 1.0, - fields: validatorRoleFields, - min_sig_member: 1.0 - }, - { - quorum: 0.0, - fields: ownerRoleFields, - min_sig_member: 0.0 - } - ], - storages: [STORAGEURL] - }, - blm: { - members: [], - validation_rules: [ - { - quorum: 0.0, - fields: [ - 'description', - 'name', - 'lastName', - ], - min_sig_member: 0.0 - } - ], - storages: [STORAGEURL] - }, - }; - - await this.getTokensFromFaucet(); - - try { - return this.createProcess( - privateData, - publicData, - roles, - ) - } catch (e) { - throw new Error(`Creating process failed:, ${e}`); - } - } - - // create a process for folder - public async createFolderProcess(folderData: any): Promise { - const myProcessId: string = this.getPairingProcessId(); - if (!myProcessId) { - throw new Error('Missing pairing id'); - } - - const privateData = { - description: 'folder', - documents: [], - notes: [], - ...folderData, - }; - const ownerRoleFields = [...Object.keys(privateData), 'roles']; - const stakeholdersRoleFields = ['documents', 'notes']; - - const roles: Record = { - owner: { - members: [myProcessId], - validation_rules: [ - { - quorum: 0.01, - fields: ownerRoleFields, - min_sig_member: 0.01, - }, - ], - storages: [STORAGEURL] - }, - stakeholder: { - members: folderData.stakeholders, - validation_rules: [ - { - quorum: 0.01, - fields: stakeholdersRoleFields, - min_sig_member: 0.01, - }, - ], - storages: [STORAGEURL] - }, - customer: { - members: [], - validation_rules: [ - { - quorum: 0.0, - fields: stakeholdersRoleFields, - min_sig_member: 0.0, - }, - ], - storages: [STORAGEURL] - } - }; - - await this.getTokensFromFaucet(); - - try { - return this.createProcess( - privateData, - {}, - roles - ) - } catch (e) { - throw new Error(`Creating folder process failed: ${e}`); - } - } - - public MOCK_NOTARY = { - at_hash: "DQLI1_Wg0853tf0qf8BYxghzIXaMBaQu4UWz07iG7o", - sub: "IDN26889949I", - profile_id: "IDN26889949I_IDN009850", - arm: "1", - iss: "https://connexion.idnot.fr/idPOAuth2/idnot_idp_v1", - given_name: "Marie", - aud: "BB715912AFEEC6D1", - nbf: "1669713096", - auth_time: "1669713195", - entity_id: "IDN009850", - name: "DUPONT", - exp: "1669720396", - iat: "1669713196", - email: "marie.dupont@notaires.fr" - }; - - // This look for the process that holds all the notaries - // private async lookForNotaryProcess(): Promise { - // const processes = await this.getProcesses(); - // for (const processId of Object.keys(processes)) { - // try { - // const process = await this.getProcess(processId); - - // const roles = this.getRoles(process); - // if (!roles) { - // console.error('Failed to getRoles'); - // return null; - // } - // const roleKeys = Object.keys(roles); - - // if (roleKeys.includes("notary")) { - // let publicData; - // const lastCommitedState = this.getLastCommitedState(process); - - // // If we don't have a commited state, the notary process might be in initialization phase - // if (lastCommitedState) { - // publicData = lastCommitedState.public_data; - // } else { - // console.log(`Fallback to first, uncommited state`); - // publicData = process.states[0].public_data; - // } - - // const publicDataKeys = Object.keys(publicData); - - // if (publicDataKeys.includes("idNotTokens")){ - // return processId; - - // } else { - // continue; - // } - - // } else { - // continue; - // } - - // } catch (e) { - // console.error(e); - // } - // } - - // return null; - // } - - // private async checkIfNotary(): Promise { - // const processes = await this.getMyProcesses(); - // if (!processes) { - // return null; - // } - // for (const processId of processes) { - // try { - // const process = await this.getProcess(processId); - // const lastCommitedState = this.getLastCommitedState(process); - - // if (lastCommitedState) { - // const fields = lastCommitedState.pcd_commitment; - // const fieldsKeys = Object.keys(fields); - // const publicData = lastCommitedState.public_data; - - // if (fieldsKeys.includes("idNot") || publicData.identityCertified) { - // console.log(`Found idNot in profile ${processId}, member is notary`); - // return processId; - // } else { - // continue; - // } - - // } else { - // continue; - // } - - // } catch (e) { - // console.error(e); - // } - // } - // return null; - // } - public async updateProcess(process: Process, privateData: Record, publicData: Record, roles: Record | null): Promise { // If roles is null, we just take the last commited state roles if (!roles) { @@ -936,8 +564,9 @@ export default class Services { if (updatedProcess.encrypted_data && Object.keys(updatedProcess.encrypted_data).length != 0) { for (const [hash, cipher] of Object.entries(updatedProcess.encrypted_data)) { - // console.log(hash); - // console.log(cipher); + // console.log('Saving encrypted data'); + // console.log(`hash: ${hash}`); + // console.log(`cipher: ${cipher}`); const blob = this.hexToBlob(cipher); try { await this.saveBlobToDb(hash, blob); @@ -1811,135 +1440,6 @@ export default class Services { return await this.updateProcess(process, {}, publicData, null); } - public async createAndSendNotaryTx(): Promise { - try { - await this.checkConnections([]); - } catch (e) { - throw e; - } - - try { - const createNotaryProcessReturn = await this.createNotaryProcess( - [], - ); - if (!createNotaryProcessReturn.updated_process) { - throw new Error('createNotaryProcessReturn returned an empty new process'); - } - await this.handleApiReturn(createNotaryProcessReturn); - - this.setProcessId(createNotaryProcessReturn.updated_process.process_id); - console.log('PROCESS NOTARY:', createNotaryProcessReturn.updated_process.process_id); - this.setStateId(createNotaryProcessReturn.updated_process.current_process.states[0].state_id); - } catch (e) { - console.error(e); - } - - try { - const createPrdUpdateReturn = await this.createPrdUpdate(this.processId!, this.stateId!); - await this.handleApiReturn(createPrdUpdateReturn); - } catch (e) { - throw new Error(`createPrdUpdate failed: ${e}`); - } - - try { - const approveChangeReturn = await this.approveChange(this.processId!, this.stateId!); - await this.handleApiReturn(approveChangeReturn); - } catch (e) { - throw new Error(`approveChange failed: ${e}`); - } - - this.processId = null; - this.stateId = null; - } - - public async createAndSendProfileTx(userData: any): Promise<{ processId: string, process: Process }> { - try { - const createProfileProcessReturn = await this.createProfileProcess( - userData, - ); - await this.handleApiReturn(createProfileProcessReturn); - - this.setProcessId(createProfileProcessReturn.updated_process!.process_id); - this.setStateId(createProfileProcessReturn.updated_process!.current_process.states[0].state_id); - } catch (e) { - throw new Error(`createProfileProcess failed: ${e}`); - } - - try { - const createPrdUpdateReturn = await this.createPrdUpdate(this.processId!, this.stateId!); - await this.handleApiReturn(createPrdUpdateReturn); - } catch (e) { - throw new Error(`createPrdUpdate failed: ${e}`); - } - - try { - const approveChangeReturn = await this.approveChange(this.processId!, this.stateId!); - await this.handleApiReturn(approveChangeReturn); - } catch (e) { - throw new Error(`approveChange failed: ${e}`); - } - - // Get the new process from db - const processId = this.processId!; - this.setProcessId(null); - this.setStateId(null); - const profileProcess = await this.getProcess(processId); - if (profileProcess) { - return {processId, process: profileProcess}; - } else { - console.error('Failed to retrieve newly created profile process'); // This shouldn't happen - return { processId, process: { states: [] } }; - } - } - - public async createAndSendFolderTx(folderData: any): Promise<{ processId: string, process: Process }> { - try { - await this.checkConnections([]); - } catch (e) { - throw e; - } - - try { - console.log("folderData", folderData); - const createFolderProcessReturn = await this.createFolderProcess( - folderData, - ); - await this.handleApiReturn(createFolderProcessReturn); - - this.setProcessId(createFolderProcessReturn.updated_process!.process_id); - this.setStateId(createFolderProcessReturn.updated_process!.current_process.states[0].state_id); - } catch (e) { - throw new Error(`createFolderProcess failed: ${e}`); - } - - try { - const createPrdUpdateReturn = await this.createPrdUpdate(this.processId!, this.stateId!); - await this.handleApiReturn(createPrdUpdateReturn); - } catch (e) { - throw new Error(`createPrdUpdate failed: ${e}`); - } - - try { - const approveChangeReturn = await this.approveChange(this.processId!, this.stateId!); - await this.handleApiReturn(approveChangeReturn); - } catch (e) { - throw new Error(`approveChange failed: ${e}`); - } - - // Get the new process from db - const processId = this.processId!; - this.setProcessId(null); - this.setStateId(null); - console.log(`createAndSendFolderTx ~ processId: ${processId}`); - const folderProcess = await this.getProcess(processId); - if (folderProcess) { - return { processId, process: folderProcess }; - } else { - console.error('Failed to retrieve newly created folder process'); // This shouldn't happen - return { processId, process: { states: [] } }; - } - } - public async generateProcessPdf(processId: string, processState: ProcessState): Promise { const pdfDoc = await PDFDocument.create(); const page = pdfDoc.addPage([595.28, 841.89]);