style: formatage Prettier sur src/
This commit is contained in:
parent
2567e2f0da
commit
93d61c1e9c
@ -158,12 +158,12 @@ async function createBackUp() {
|
|||||||
const service = await Services.getInstance();
|
const service = await Services.getInstance();
|
||||||
const backUp = await service.createBackUp();
|
const backUp = await service.createBackUp();
|
||||||
if (!backUp) {
|
if (!backUp) {
|
||||||
console.error("No device to backup");
|
console.error('No device to backup');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const backUpJson = JSON.stringify(backUp, null, 2)
|
const backUpJson = JSON.stringify(backUp, null, 2);
|
||||||
const blob = new Blob([backUpJson], { type: 'application/json' });
|
const blob = new Blob([backUpJson], { type: 'application/json' });
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
|
|
||||||
@ -201,7 +201,7 @@ async function disconnect() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
const registrations = await navigator.serviceWorker.getRegistrations();
|
||||||
await Promise.all(registrations.map(registration => registration.unregister()));
|
await Promise.all(registrations.map((registration) => registration.unregister()));
|
||||||
console.log('Service worker unregistered');
|
console.log('Service worker unregistered');
|
||||||
|
|
||||||
await navigate('home');
|
await navigate('home');
|
||||||
@ -209,7 +209,6 @@ async function disconnect() {
|
|||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
window.location.href = window.location.origin;
|
window.location.href = window.location.origin;
|
||||||
}, 100);
|
}, 100);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error during disconnect:', error);
|
console.error('Error during disconnect:', error);
|
||||||
// force reload
|
// force reload
|
||||||
|
@ -1,8 +1,6 @@
|
|||||||
<div id="waiting-modal" class="modal">
|
<div id="waiting-modal" class="modal">
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
<div class="modal-title">Login</div>
|
<div class="modal-title">Login</div>
|
||||||
<div class="message">
|
<div class="message">Waiting for Device 2...</div>
|
||||||
Waiting for Device 2...
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
@ -1,9 +1,7 @@
|
|||||||
<div id="validation-modal" class="validation-modal">
|
<div id="validation-modal" class="validation-modal">
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
<div class="modal-title">Validate Process {{processId}}</div>
|
<div class="modal-title">Validate Process {{processId}}</div>
|
||||||
<div class="validation-box">
|
<div class="validation-box"></div>
|
||||||
|
|
||||||
</div>
|
|
||||||
<div class="modal-action">
|
<div class="modal-action">
|
||||||
<button onclick="validate()">Validate</button>
|
<button onclick="validate()">Validate</button>
|
||||||
</div>
|
</div>
|
||||||
|
@ -7,9 +7,9 @@ async function validate() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function initValidationModal(processDiffs: any) {
|
export async function initValidationModal(processDiffs: any) {
|
||||||
console.log("🚀 ~ initValidationModal ~ processDiffs:", processDiffs)
|
console.log('🚀 ~ initValidationModal ~ processDiffs:', processDiffs);
|
||||||
for (const diff of processDiffs.diffs) {
|
for (const diff of processDiffs.diffs) {
|
||||||
let diffs = ''
|
let diffs = '';
|
||||||
for (const value of diff) {
|
for (const value of diff) {
|
||||||
diffs += `
|
diffs += `
|
||||||
<div class="radio-buttons">
|
<div class="radio-buttons">
|
||||||
@ -30,7 +30,7 @@ for(const diff of processDiffs.diffs) {
|
|||||||
<pre>+${value.new_value}</pre>
|
<pre>+${value.new_value}</pre>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
`
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const state = `
|
const state = `
|
||||||
@ -40,9 +40,9 @@ for(const diff of processDiffs.diffs) {
|
|||||||
${diffs}
|
${diffs}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
`
|
`;
|
||||||
const box = document.querySelector('.validation-box')
|
const box = document.querySelector('.validation-box');
|
||||||
if(box) box.innerHTML += state
|
if (box) box.innerHTML += state;
|
||||||
}
|
}
|
||||||
document.querySelectorAll('.expansion-panel-header').forEach((header) => {
|
document.querySelectorAll('.expansion-panel-header').forEach((header) => {
|
||||||
header.addEventListener('click', function (event) {
|
header.addEventListener('click', function (event) {
|
||||||
|
@ -1,42 +1,25 @@
|
|||||||
<div id="validation-rule-modal" style="
|
<div id="validation-rule-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); display: none; justify-content: center; align-items: center; z-index: 9999">
|
||||||
position: fixed;
|
<div style="background: white; padding: 2rem; border-radius: 0.5rem; width: 400px; max-width: 90%; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3)">
|
||||||
top: 0; left: 0; right: 0; bottom: 0;
|
<h2 style="font-size: 1.2rem; font-weight: bold; margin-bottom: 1rem">Add Validation Rule</h2>
|
||||||
background: rgba(0,0,0,0.5);
|
|
||||||
display: none;
|
|
||||||
justify-content: center;
|
|
||||||
align-items: center;
|
|
||||||
z-index: 9999;
|
|
||||||
">
|
|
||||||
<div style="
|
|
||||||
background: white;
|
|
||||||
padding: 2rem;
|
|
||||||
border-radius: 0.5rem;
|
|
||||||
width: 400px;
|
|
||||||
max-width: 90%;
|
|
||||||
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
|
|
||||||
">
|
|
||||||
<h2 style="font-size: 1.2rem; font-weight: bold; margin-bottom: 1rem;">
|
|
||||||
Add Validation Rule
|
|
||||||
</h2>
|
|
||||||
|
|
||||||
<label style="display: block; margin-bottom: 0.5rem;">
|
<label style="display: block; margin-bottom: 0.5rem">
|
||||||
Quorum:
|
Quorum:
|
||||||
<input id="vr-quorum" type="number" style="width: 100%; padding: 0.5rem; margin-top: 0.25rem;" />
|
<input id="vr-quorum" type="number" style="width: 100%; padding: 0.5rem; margin-top: 0.25rem" />
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<label style="display: block; margin-bottom: 0.5rem;">
|
<label style="display: block; margin-bottom: 0.5rem">
|
||||||
Min Sig Member:
|
Min Sig Member:
|
||||||
<input id="vr-minsig" type="number" style="width: 100%; padding: 0.5rem; margin-top: 0.25rem;" />
|
<input id="vr-minsig" type="number" style="width: 100%; padding: 0.5rem; margin-top: 0.25rem" />
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<label style="display: block; margin-bottom: 1rem;">
|
<label style="display: block; margin-bottom: 1rem">
|
||||||
Fields (comma-separated):
|
Fields (comma-separated):
|
||||||
<input id="vr-fields" type="text" placeholder="e.g. field1, field2" style="width: 100%; padding: 0.5rem; margin-top: 0.25rem;" />
|
<input id="vr-fields" type="text" placeholder="e.g. field1, field2" style="width: 100%; padding: 0.5rem; margin-top: 0.25rem" />
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<div style="display: flex; justify-content: flex-end; gap: 1rem;">
|
<div style="display: flex; justify-content: flex-end; gap: 1rem">
|
||||||
<button id="vr-cancel" style="padding: 0.5rem 1rem;">Cancel</button>
|
<button id="vr-cancel" style="padding: 0.5rem 1rem">Cancel</button>
|
||||||
<button id="vr-submit" style="padding: 0.5rem 1rem; background-color: #4f46e5; color: white; border: none; border-radius: 0.375rem;">Add</button>
|
<button id="vr-submit" style="padding: 0.5rem 1rem; background-color: #4f46e5; color: white; border: none; border-radius: 0.375rem">Add</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -52,7 +52,10 @@ export function showValidationRuleModal(onSubmit: (rule: ValidationRule) => void
|
|||||||
const rule: ValidationRule = {
|
const rule: ValidationRule = {
|
||||||
quorum: parseInt(quorumInput.value),
|
quorum: parseInt(quorumInput.value),
|
||||||
min_sig_member: parseInt(minsigInput.value),
|
min_sig_member: parseInt(minsigInput.value),
|
||||||
fields: fieldsInput.value.split(',').map(f => f.trim()).filter(Boolean),
|
fields: fieldsInput.value
|
||||||
|
.split(',')
|
||||||
|
.map((f) => f.trim())
|
||||||
|
.filter(Boolean),
|
||||||
};
|
};
|
||||||
|
|
||||||
modal.style.display = 'none';
|
modal.style.display = 'none';
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
import { Device, Process, SecretsStore } from "pkg/sdk_client";
|
import { Device, Process, SecretsStore } from 'pkg/sdk_client';
|
||||||
|
|
||||||
export interface BackUp {
|
export interface BackUp {
|
||||||
device: Device,
|
device: Device;
|
||||||
secrets: SecretsStore,
|
secrets: SecretsStore;
|
||||||
processes: Record<string, Process>,
|
processes: Record<string, Process>;
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<!DOCTYPE html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<title>Account</title>
|
<title>Account</title>
|
||||||
|
@ -197,7 +197,6 @@ class AccountElement extends HTMLElement {
|
|||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
|
||||||
window.showPairing = () => this.showPairing();
|
window.showPairing = () => this.showPairing();
|
||||||
window.showWallet = () => this.showWallet();
|
window.showWallet = () => this.showWallet();
|
||||||
window.showProcess = () => this.showProcess();
|
window.showProcess = () => this.showProcess();
|
||||||
@ -281,7 +280,6 @@ class AccountElement extends HTMLElement {
|
|||||||
}, 3000);
|
}, 3000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Fonctions de gestion des comptes et de l'interface utilisateur
|
// Fonctions de gestion des comptes et de l'interface utilisateur
|
||||||
private confirmDeleteAccount(): void {
|
private confirmDeleteAccount(): void {
|
||||||
const modal = document.createElement('div');
|
const modal = document.createElement('div');
|
||||||
@ -346,7 +344,6 @@ private loadSavedBanner(): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private closeNotificationPopup(event: Event): void {
|
private closeNotificationPopup(event: Event): void {
|
||||||
const target = event.target as HTMLElement;
|
const target = event.target as HTMLElement;
|
||||||
const isOverlay = target.classList.contains('notification-popup-overlay');
|
const isOverlay = target.classList.contains('notification-popup-overlay');
|
||||||
@ -358,10 +355,10 @@ private closeNotificationPopup(event: Event): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private markAsRead(processName: string, messageId: number, element: HTMLElement): void {
|
private markAsRead(processName: string, messageId: number, element: HTMLElement): void {
|
||||||
const process = mockProcessRows.find(p => p.process === processName);
|
const process = mockProcessRows.find((p) => p.process === processName);
|
||||||
if (!process) return;
|
if (!process) return;
|
||||||
|
|
||||||
const message = process.notification.messages.find(m => m.id === messageId);
|
const message = process.notification.messages.find((m) => m.id === messageId);
|
||||||
if (!message || message.read) return;
|
if (!message || message.read) return;
|
||||||
|
|
||||||
message.read = true;
|
message.read = true;
|
||||||
@ -394,7 +391,7 @@ private markAsRead(processName: string, messageId: number, element: HTMLElement)
|
|||||||
// Fonctions de gestion des données et de l'interface
|
// Fonctions de gestion des données et de l'interface
|
||||||
private calculateNotifications(messages: NotificationMessage[]): { unread: number; total: number } {
|
private calculateNotifications(messages: NotificationMessage[]): { unread: number; total: number } {
|
||||||
const total = messages.length;
|
const total = messages.length;
|
||||||
const unread = messages.filter(msg => !msg.read).length;
|
const unread = messages.filter((msg) => !msg.read).length;
|
||||||
return { unread, total };
|
return { unread, total };
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -412,8 +409,8 @@ private exportRecovery(): void {
|
|||||||
// Ajouter des styles personnalisés
|
// Ajouter des styles personnalisés
|
||||||
customClass: {
|
customClass: {
|
||||||
container: 'recovery-popup-container',
|
container: 'recovery-popup-container',
|
||||||
popup: 'recovery-popup'
|
popup: 'recovery-popup',
|
||||||
}
|
},
|
||||||
}).then((result) => {
|
}).then((result) => {
|
||||||
if (result.isConfirmed) {
|
if (result.isConfirmed) {
|
||||||
const recoveryWords = this.generateRecoveryWords();
|
const recoveryWords = this.generateRecoveryWords();
|
||||||
@ -423,12 +420,16 @@ private exportRecovery(): void {
|
|||||||
title: 'Your Recovery Words',
|
title: 'Your Recovery Words',
|
||||||
html: `
|
html: `
|
||||||
<div class="recovery-words-container">
|
<div class="recovery-words-container">
|
||||||
${recoveryWords.map((word, index) => `
|
${recoveryWords
|
||||||
|
.map(
|
||||||
|
(word, index) => `
|
||||||
<div class="recovery-word">
|
<div class="recovery-word">
|
||||||
<span class="word-number">${index + 1}.</span>
|
<span class="word-number">${index + 1}.</span>
|
||||||
<span class="word">${word}</span>
|
<span class="word">${word}</span>
|
||||||
</div>
|
</div>
|
||||||
`).join('')}
|
`,
|
||||||
|
)
|
||||||
|
.join('')}
|
||||||
</div>
|
</div>
|
||||||
<div class="recovery-warning">
|
<div class="recovery-warning">
|
||||||
Please write these words down carefully. They will be needed to recover your account.
|
Please write these words down carefully. They will be needed to recover your account.
|
||||||
@ -441,8 +442,8 @@ private exportRecovery(): void {
|
|||||||
allowEscapeKey: false,
|
allowEscapeKey: false,
|
||||||
customClass: {
|
customClass: {
|
||||||
container: 'recovery-popup-container',
|
container: 'recovery-popup-container',
|
||||||
popup: 'recovery-popup'
|
popup: 'recovery-popup',
|
||||||
}
|
},
|
||||||
}).then((result) => {
|
}).then((result) => {
|
||||||
if (result.isConfirmed) {
|
if (result.isConfirmed) {
|
||||||
// Stocker l'état du bouton dans le localStorage
|
// Stocker l'état du bouton dans le localStorage
|
||||||
@ -461,10 +462,7 @@ private exportRecovery(): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private generateRecoveryWords(): string[] {
|
private generateRecoveryWords(): string[] {
|
||||||
const wordsList = [
|
const wordsList = ['apple', 'banana', 'orange', 'grape', 'kiwi', 'mango', 'peach', 'plum', 'lemon', 'lime', 'cherry', 'melon', 'pear', 'fig', 'date', 'berry'];
|
||||||
'apple', 'banana', 'orange', 'grape', 'kiwi', 'mango', 'peach', 'plum',
|
|
||||||
'lemon', 'lime', 'cherry', 'melon', 'pear', 'fig', 'date', 'berry'
|
|
||||||
];
|
|
||||||
const recoveryWords: string[] = [];
|
const recoveryWords: string[] = [];
|
||||||
while (recoveryWords.length < 4) {
|
while (recoveryWords.length < 4) {
|
||||||
const randomWord = wordsList[Math.floor(Math.random() * wordsList.length)];
|
const randomWord = wordsList[Math.floor(Math.random() * wordsList.length)];
|
||||||
@ -597,7 +595,7 @@ private async addRowPairing(): Promise<void> {
|
|||||||
const newRow: Row = {
|
const newRow: Row = {
|
||||||
column1: spAddress,
|
column1: spAddress,
|
||||||
column2: deviceName,
|
column2: deviceName,
|
||||||
column3: spEmojis || ''
|
column3: spEmojis || '',
|
||||||
};
|
};
|
||||||
|
|
||||||
const storageKey = STORAGE_KEYS[currentMode];
|
const storageKey = STORAGE_KEYS[currentMode];
|
||||||
@ -622,7 +620,9 @@ private updateTableContent(rows: Row[]): void {
|
|||||||
const tbody = this.shadowRoot?.querySelector('#pairing-table tbody');
|
const tbody = this.shadowRoot?.querySelector('#pairing-table tbody');
|
||||||
if (!tbody) return;
|
if (!tbody) return;
|
||||||
|
|
||||||
tbody.innerHTML = rows.map(row => `
|
tbody.innerHTML = rows
|
||||||
|
.map(
|
||||||
|
(row) => `
|
||||||
<tr>
|
<tr>
|
||||||
<td class="device-name" onclick="window.editDeviceName(this)">${row.column2}</td>
|
<td class="device-name" onclick="window.editDeviceName(this)">${row.column2}</td>
|
||||||
<td>${row.column3}</td>
|
<td>${row.column3}</td>
|
||||||
@ -641,19 +641,19 @@ private updateTableContent(rows: Row[]): void {
|
|||||||
</button>
|
</button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
`).join('');
|
`,
|
||||||
|
)
|
||||||
|
.join('');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private confirmRowPairing(): void {
|
private confirmRowPairing(): void {
|
||||||
if (!currentRow) return;
|
if (!currentRow) return;
|
||||||
|
|
||||||
const inputs = currentRow.getElementsByTagName('input');
|
const inputs = currentRow.getElementsByTagName('input');
|
||||||
const values: string[] = Array.from(inputs).map(input => input.value.trim());
|
const values: string[] = Array.from(inputs).map((input) => input.value.trim());
|
||||||
|
|
||||||
// Vérification des champs vides
|
// Vérification des champs vides
|
||||||
if (values.some(value => value === '')) {
|
if (values.some((value) => value === '')) {
|
||||||
this.showAlert('Please fill in all fields');
|
this.showAlert('Please fill in all fields');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -667,7 +667,7 @@ private confirmRowPairing(): void {
|
|||||||
const newRow: Row = {
|
const newRow: Row = {
|
||||||
column1: values[0],
|
column1: values[0],
|
||||||
column2: values[1],
|
column2: values[1],
|
||||||
column3: values[2]
|
column3: values[2],
|
||||||
};
|
};
|
||||||
|
|
||||||
const storageKey = STORAGE_KEYS[currentMode];
|
const storageKey = STORAGE_KEYS[currentMode];
|
||||||
@ -858,13 +858,14 @@ private async showProcess(): Promise<void> {
|
|||||||
const service = await Services.getInstance();
|
const service = await Services.getInstance();
|
||||||
const myProcesses = await service.getMyProcesses();
|
const myProcesses = await service.getMyProcesses();
|
||||||
if (myProcesses && myProcesses.length != 0) {
|
if (myProcesses && myProcesses.length != 0) {
|
||||||
const myProcessesDataUnfiltered: { name: string, publicData: Record<string, any> }[] = await Promise.all(myProcesses.map(async processId => {
|
const myProcessesDataUnfiltered: { name: string; publicData: Record<string, any> }[] = await Promise.all(
|
||||||
|
myProcesses.map(async (processId) => {
|
||||||
const process = await service.getProcess(processId);
|
const process = await service.getProcess(processId);
|
||||||
const lastState = process ? service.getLastCommitedState(process) : null;
|
const lastState = process ? service.getLastCommitedState(process) : null;
|
||||||
if (!lastState) {
|
if (!lastState) {
|
||||||
return {
|
return {
|
||||||
name: '',
|
name: '',
|
||||||
publicData: {}
|
publicData: {},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const description = await service.decryptAttribute(processId, lastState, 'description');
|
const description = await service.decryptAttribute(processId, lastState, 'description');
|
||||||
@ -873,17 +874,16 @@ private async showProcess(): Promise<void> {
|
|||||||
if (!publicData) {
|
if (!publicData) {
|
||||||
return {
|
return {
|
||||||
name: '',
|
name: '',
|
||||||
publicData: {}
|
publicData: {},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
name: name,
|
name: name,
|
||||||
publicData: publicData
|
publicData: publicData,
|
||||||
};
|
};
|
||||||
}));
|
}),
|
||||||
const myProcessesData = myProcessesDataUnfiltered.filter(
|
|
||||||
(p) => p.name !== '' && Object.keys(p.publicData).length != 0
|
|
||||||
);
|
);
|
||||||
|
const myProcessesData = myProcessesDataUnfiltered.filter((p) => p.name !== '' && Object.keys(p.publicData).length != 0);
|
||||||
|
|
||||||
createProcessTab(container, myProcessesData);
|
createProcessTab(container, myProcessesData);
|
||||||
} else {
|
} else {
|
||||||
@ -893,21 +893,24 @@ private async showProcess(): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private showProcessNotifications(processName: string): void {
|
private showProcessNotifications(processName: string): void {
|
||||||
const process = mockProcessRows.find(p => p.process === processName);
|
const process = mockProcessRows.find((p) => p.process === processName);
|
||||||
if (!process) return;
|
if (!process) return;
|
||||||
|
|
||||||
const modal = document.createElement('div');
|
const modal = document.createElement('div');
|
||||||
modal.className = 'notifications-modal';
|
modal.className = 'notifications-modal';
|
||||||
|
|
||||||
let notificationsList = process.notification.messages.map(msg => `
|
let notificationsList = process.notification.messages
|
||||||
|
.map(
|
||||||
|
(msg) => `
|
||||||
<div class="notification-item ${msg.read ? 'read' : 'unread'}"
|
<div class="notification-item ${msg.read ? 'read' : 'unread'}"
|
||||||
onclick="window.markAsRead('${processName}', ${msg.id}, this)">
|
onclick="window.markAsRead('${processName}', ${msg.id}, this)">
|
||||||
<div class="notification-status">
|
<div class="notification-status">
|
||||||
${msg.read ?
|
${
|
||||||
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="16" height="16" fill="green">
|
msg.read
|
||||||
|
? `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="16" height="16" fill="green">
|
||||||
<path d="M438.6 105.4c12.5 12.5 12.5 32.8 0 45.3l-256 256c-12.5 12.5-32.8 12.5-45.3 0l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L160 338.7 393.4 105.4c12.5-12.5 32.8-12.5 45.3 0z"/>
|
<path d="M438.6 105.4c12.5 12.5 12.5 32.8 0 45.3l-256 256c-12.5 12.5-32.8 12.5-45.3 0l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L160 338.7 393.4 105.4c12.5-12.5 32.8-12.5 45.3 0z"/>
|
||||||
</svg>` :
|
</svg>`
|
||||||
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="16" height="16" fill="black">
|
: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="16" height="16" fill="black">
|
||||||
<path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512z"/>
|
<path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512z"/>
|
||||||
</svg>`
|
</svg>`
|
||||||
}
|
}
|
||||||
@ -917,7 +920,9 @@ private showProcessNotifications(processName: string): void {
|
|||||||
<small>${msg.date}</small>
|
<small>${msg.date}</small>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
`).join('');
|
`,
|
||||||
|
)
|
||||||
|
.join('');
|
||||||
|
|
||||||
if (process.notification.messages.length === 0) {
|
if (process.notification.messages.length === 0) {
|
||||||
notificationsList = '<p>No notifications</p>';
|
notificationsList = '<p>No notifications</p>';
|
||||||
@ -949,13 +954,11 @@ private showProcessNotifications(processName: string): void {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private handleLogout(): void {
|
private handleLogout(): void {
|
||||||
localStorage.clear();
|
localStorage.clear();
|
||||||
window.location.href = '../login/login.html';
|
window.location.href = '../login/login.html';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Fonctions de gestion des contrats
|
// Fonctions de gestion des contrats
|
||||||
private showContractPopup(contractId: string, event?: Event) {
|
private showContractPopup(contractId: string, event?: Event) {
|
||||||
if (event) {
|
if (event) {
|
||||||
@ -980,7 +983,7 @@ private showContractPopup(contractId: string, event?: Event) {
|
|||||||
<p><strong>Parties:</strong> ${contract.parties.join(', ')}</p>
|
<p><strong>Parties:</strong> ${contract.parties.join(', ')}</p>
|
||||||
<p><strong>Terms:</strong></p>
|
<p><strong>Terms:</strong></p>
|
||||||
<ul>
|
<ul>
|
||||||
${contract.terms.map(term => `<li>${term}</li>`).join('')}
|
${contract.terms.map((term) => `<li>${term}</li>`).join('')}
|
||||||
</ul>
|
</ul>
|
||||||
<p><strong>Content:</strong> ${contract.content}</p>
|
<p><strong>Content:</strong> ${contract.content}</p>
|
||||||
</div>
|
</div>
|
||||||
@ -1001,7 +1004,7 @@ private showContractPopup(contractId: string, event?: Event) {
|
|||||||
// Fonction utilitaire pour cacher tous les contenus
|
// Fonction utilitaire pour cacher tous les contenus
|
||||||
private hideAllContent(): void {
|
private hideAllContent(): void {
|
||||||
const contents = ['pairing-content', 'wallet-content', 'process-content', 'process-creation-content', 'data-content', 'document-validation-content'];
|
const contents = ['pairing-content', 'wallet-content', 'process-content', 'process-creation-content', 'data-content', 'document-validation-content'];
|
||||||
contents.forEach(id => {
|
contents.forEach((id) => {
|
||||||
const element = this.shadowRoot?.getElementById(id);
|
const element = this.shadowRoot?.getElementById(id);
|
||||||
if (element) {
|
if (element) {
|
||||||
element.style.display = 'none';
|
element.style.display = 'none';
|
||||||
@ -1063,15 +1066,14 @@ private async showPairing(): Promise<void> {
|
|||||||
const pairingProcess = await service.getProcess(pairingProcessId);
|
const pairingProcess = await service.getProcess(pairingProcessId);
|
||||||
console.log('Pairing Process:', pairingProcess);
|
console.log('Pairing Process:', pairingProcess);
|
||||||
|
|
||||||
const userName = pairingProcess?.states?.[0]?.public_data?.memberPublicName
|
const userName = pairingProcess?.states?.[0]?.public_data?.memberPublicName || localStorage.getItem('userName');
|
||||||
|| localStorage.getItem('userName')
|
|
||||||
|
|
||||||
console.log('Username found:', userName);
|
console.log('Username found:', userName);
|
||||||
|
|
||||||
const newRow = {
|
const newRow = {
|
||||||
column1: spAddress,
|
column1: spAddress,
|
||||||
column2: userName,
|
column2: userName,
|
||||||
column3: emojis
|
column3: emojis,
|
||||||
};
|
};
|
||||||
rows = [newRow, ...rows];
|
rows = [newRow, ...rows];
|
||||||
localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows));
|
localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows));
|
||||||
@ -1080,7 +1082,7 @@ private async showPairing(): Promise<void> {
|
|||||||
const newRow = {
|
const newRow = {
|
||||||
column1: spAddress,
|
column1: spAddress,
|
||||||
column2: 'This Device',
|
column2: 'This Device',
|
||||||
column3: emojis
|
column3: emojis,
|
||||||
};
|
};
|
||||||
rows = [newRow, ...rows];
|
rows = [newRow, ...rows];
|
||||||
localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows));
|
localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows));
|
||||||
@ -1128,18 +1130,21 @@ private showWallet(): void {
|
|||||||
this.updateWalletTableContent(rows);
|
this.updateWalletTableContent(rows);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private updateWalletTableContent(rows: WalletRow[]): void {
|
private updateWalletTableContent(rows: WalletRow[]): void {
|
||||||
const tbody = this.shadowRoot?.querySelector('#wallet-table tbody');
|
const tbody = this.shadowRoot?.querySelector('#wallet-table tbody');
|
||||||
if (!tbody) return;
|
if (!tbody) return;
|
||||||
|
|
||||||
tbody.innerHTML = rows.map(row => `
|
tbody.innerHTML = rows
|
||||||
|
.map(
|
||||||
|
(row) => `
|
||||||
<tr>
|
<tr>
|
||||||
<td>${row.column1}</td>
|
<td>${row.column1}</td>
|
||||||
<td>${row.column2}</td>
|
<td>${row.column2}</td>
|
||||||
<td class="device-name" onclick="editDeviceName(this)">${row.column3}</td>
|
<td class="device-name" onclick="editDeviceName(this)">${row.column3}</td>
|
||||||
</tr>
|
</tr>
|
||||||
`).join('');
|
`,
|
||||||
|
)
|
||||||
|
.join('');
|
||||||
}
|
}
|
||||||
|
|
||||||
private showData(): void {
|
private showData(): void {
|
||||||
@ -1188,7 +1193,7 @@ private addWalletRow(): void {
|
|||||||
currentRow = table.insertRow();
|
currentRow = table.insertRow();
|
||||||
const placeholders = ['Label', 'Wallet', 'Type'];
|
const placeholders = ['Label', 'Wallet', 'Type'];
|
||||||
|
|
||||||
placeholders.forEach(placeholder => {
|
placeholders.forEach((placeholder) => {
|
||||||
const cell = currentRow!.insertCell();
|
const cell = currentRow!.insertCell();
|
||||||
const input = document.createElement('input');
|
const input = document.createElement('input');
|
||||||
input.type = 'text';
|
input.type = 'text';
|
||||||
@ -1215,13 +1220,13 @@ private confirmWalletRow(): void {
|
|||||||
if (!currentRow) return;
|
if (!currentRow) return;
|
||||||
|
|
||||||
const inputs = Array.from(currentRow.getElementsByTagName('input'));
|
const inputs = Array.from(currentRow.getElementsByTagName('input'));
|
||||||
const allFieldsFilled = inputs.every(input => input.value.trim() !== '');
|
const allFieldsFilled = inputs.every((input) => input.value.trim() !== '');
|
||||||
|
|
||||||
if (allFieldsFilled) {
|
if (allFieldsFilled) {
|
||||||
const newRow: WalletRow = {
|
const newRow: WalletRow = {
|
||||||
column1: inputs[0].value.trim(),
|
column1: inputs[0].value.trim(),
|
||||||
column2: inputs[1].value.trim(),
|
column2: inputs[1].value.trim(),
|
||||||
column3: inputs[2].value.trim()
|
column3: inputs[2].value.trim(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const rows = JSON.parse(localStorage.getItem(STORAGE_KEYS.wallet) || '[]');
|
const rows = JSON.parse(localStorage.getItem(STORAGE_KEYS.wallet) || '[]');
|
||||||
@ -1250,15 +1255,15 @@ private cancelWalletRow(): void {
|
|||||||
buttonContainer.innerHTML = `
|
buttonContainer.innerHTML = `
|
||||||
<button class="add-row-button button-style" onclick="window.addWalletRow()">Add a line</button>
|
<button class="add-row-button button-style" onclick="window.addWalletRow()">Add a line</button>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private updateDataTableContent(rows: DataRow[]): void {
|
private updateDataTableContent(rows: DataRow[]): void {
|
||||||
const tbody = this.shadowRoot?.querySelector('#data-table tbody');
|
const tbody = this.shadowRoot?.querySelector('#data-table tbody');
|
||||||
if (!tbody) return;
|
if (!tbody) return;
|
||||||
|
|
||||||
tbody.innerHTML = rows.map(row => `
|
tbody.innerHTML = rows
|
||||||
|
.map(
|
||||||
|
(row) => `
|
||||||
<tr>
|
<tr>
|
||||||
<td>${row.column1}</td>
|
<td>${row.column1}</td>
|
||||||
<td>${row.column2}</td>
|
<td>${row.column2}</td>
|
||||||
@ -1269,7 +1274,9 @@ private updateDataTableContent(rows: DataRow[]): void {
|
|||||||
<a href="javascript:void(0)" onclick="window.showContractPopup('${row.column6}'); return false;">${row.column6}</a>
|
<a href="javascript:void(0)" onclick="window.showContractPopup('${row.column6}'); return false;">${row.column6}</a>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
`).join('');
|
`,
|
||||||
|
)
|
||||||
|
.join('');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fonctions de gestion de l'avatar et de la bannière
|
// Fonctions de gestion de l'avatar et de la bannière
|
||||||
@ -1504,12 +1511,7 @@ private updateNavbarLastName(lastName: string): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private updateProfilePreview(data: {
|
private updateProfilePreview(data: { avatar?: string; banner?: string; name?: string; lastName?: string }): void {
|
||||||
avatar?: string,
|
|
||||||
banner?: string,
|
|
||||||
name?: string,
|
|
||||||
lastName?: string
|
|
||||||
}): void {
|
|
||||||
if (data.avatar) {
|
if (data.avatar) {
|
||||||
const previewAvatar = this.shadowRoot?.querySelector('.preview-avatar') as HTMLImageElement;
|
const previewAvatar = this.shadowRoot?.querySelector('.preview-avatar') as HTMLImageElement;
|
||||||
if (previewAvatar) previewAvatar.src = data.avatar;
|
if (previewAvatar) previewAvatar.src = data.avatar;
|
||||||
@ -1538,7 +1540,7 @@ private initializeEventListeners() {
|
|||||||
|
|
||||||
const editableFields = this.shadowRoot?.querySelectorAll<HTMLElement>('.editable');
|
const editableFields = this.shadowRoot?.querySelectorAll<HTMLElement>('.editable');
|
||||||
if (editableFields) {
|
if (editableFields) {
|
||||||
editableFields.forEach(field => {
|
editableFields.forEach((field) => {
|
||||||
field.addEventListener('click', () => {
|
field.addEventListener('click', () => {
|
||||||
if (!field.classList.contains('editing')) {
|
if (!field.classList.contains('editing')) {
|
||||||
const currentValue = field.textContent || '';
|
const currentValue = field.textContent || '';
|
||||||
|
@ -47,8 +47,8 @@ export function getDocumentValidation(container: HTMLElement) {
|
|||||||
file: null,
|
file: null,
|
||||||
fileHash: null,
|
fileHash: null,
|
||||||
certificate: null,
|
certificate: null,
|
||||||
commitmentHashes: []
|
commitmentHashes: [],
|
||||||
}
|
};
|
||||||
|
|
||||||
container.innerHTML = '';
|
container.innerHTML = '';
|
||||||
container.style.cssText = `
|
container.style.cssText = `
|
||||||
@ -60,11 +60,7 @@ export function getDocumentValidation(container: HTMLElement) {
|
|||||||
gap: 2rem;
|
gap: 2rem;
|
||||||
`;
|
`;
|
||||||
|
|
||||||
function createDropButton(
|
function createDropButton(label: string, onDrop: (file: File, updateVisuals: (file: File) => void) => void, accept: string = '*/*'): HTMLElement {
|
||||||
label: string,
|
|
||||||
onDrop: (file: File, updateVisuals: (file: File) => void) => void,
|
|
||||||
accept: string = '*/*'
|
|
||||||
): HTMLElement {
|
|
||||||
const wrapper = document.createElement('div');
|
const wrapper = document.createElement('div');
|
||||||
wrapper.style.cssText = `
|
wrapper.style.cssText = `
|
||||||
width: 200px;
|
width: 200px;
|
||||||
@ -120,7 +116,7 @@ export function getDocumentValidation(container: HTMLElement) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// === Handle drag-and-drop ===
|
// === Handle drag-and-drop ===
|
||||||
wrapper.ondragover = e => {
|
wrapper.ondragover = (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
wrapper.style.background = '#e0e0e0';
|
wrapper.style.background = '#e0e0e0';
|
||||||
};
|
};
|
||||||
@ -129,7 +125,7 @@ export function getDocumentValidation(container: HTMLElement) {
|
|||||||
wrapper.style.background = '#f8f8f8';
|
wrapper.style.background = '#f8f8f8';
|
||||||
};
|
};
|
||||||
|
|
||||||
wrapper.ondrop = e => {
|
wrapper.ondrop = (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
wrapper.style.background = '#f8f8f8';
|
wrapper.style.background = '#f8f8f8';
|
||||||
|
|
||||||
@ -163,17 +159,10 @@ export function getDocumentValidation(container: HTMLElement) {
|
|||||||
try {
|
try {
|
||||||
const text = await file.text();
|
const text = await file.text();
|
||||||
const json = JSON.parse(text);
|
const json = JSON.parse(text);
|
||||||
if (
|
if (typeof json === 'object' && json !== null && typeof json.pcd_commitment === 'object' && typeof json.state_id === 'string') {
|
||||||
typeof json === 'object' &&
|
|
||||||
json !== null &&
|
|
||||||
typeof json.pcd_commitment === 'object' &&
|
|
||||||
typeof json.state_id === 'string'
|
|
||||||
) {
|
|
||||||
state.certificate = json as ProcessState;
|
state.certificate = json as ProcessState;
|
||||||
|
|
||||||
state.commitmentHashes = Object.values(json.pcd_commitment).map((h: any) =>
|
state.commitmentHashes = Object.values(json.pcd_commitment).map((h: any) => (h as string).toLowerCase());
|
||||||
(h as string).toLowerCase()
|
|
||||||
);
|
|
||||||
|
|
||||||
updateVisuals(file);
|
updateVisuals(file);
|
||||||
console.log('Loaded certificate, extracted hashes:', state.commitmentHashes);
|
console.log('Loaded certificate, extracted hashes:', state.commitmentHashes);
|
||||||
@ -200,7 +189,7 @@ export function getDocumentValidation(container: HTMLElement) {
|
|||||||
// We take the commited_in and all pcd_commitment keys to reconstruct all the possible hash
|
// We take the commited_in and all pcd_commitment keys to reconstruct all the possible hash
|
||||||
const fileBlob = {
|
const fileBlob = {
|
||||||
type: state.file.type,
|
type: state.file.type,
|
||||||
data: new Uint8Array(await state.file.arrayBuffer())
|
data: new Uint8Array(await state.file.arrayBuffer()),
|
||||||
};
|
};
|
||||||
const service = await Services.getInstance();
|
const service = await Services.getInstance();
|
||||||
const commitedIn = state.certificate.commited_in;
|
const commitedIn = state.certificate.commited_in;
|
||||||
@ -280,7 +269,7 @@ export function getDocumentValidation(container: HTMLElement) {
|
|||||||
|
|
||||||
for (const label of Object.keys(state.certificate.pcd_commitment)) {
|
for (const label of Object.keys(state.certificate.pcd_commitment)) {
|
||||||
// Compute the hash for this label
|
// Compute the hash for this label
|
||||||
console.log(`Computing hash with label ${label}`)
|
console.log(`Computing hash with label ${label}`);
|
||||||
const fileHex = service.getHashForFile(commitedIn, label, fileBlob);
|
const fileHex = service.getHashForFile(commitedIn, label, fileBlob);
|
||||||
console.log(`Found hash ${fileHex}`);
|
console.log(`Found hash ${fileHex}`);
|
||||||
found = state.commitmentHashes.includes(fileHex);
|
found = state.commitmentHashes.includes(fileHex);
|
||||||
|
@ -33,14 +33,14 @@ export function createKeyValueSection(title: string, id: string, isRoleSection =
|
|||||||
validationRules: ValidationRule[];
|
validationRules: ValidationRule[];
|
||||||
}[] = [];
|
}[] = [];
|
||||||
type fileBlob = {
|
type fileBlob = {
|
||||||
type: string,
|
type: string;
|
||||||
data: Uint8Array
|
data: Uint8Array;
|
||||||
};
|
};
|
||||||
const nonRoleRowStates: {
|
const nonRoleRowStates: {
|
||||||
keyInput: HTMLInputElement,
|
keyInput: HTMLInputElement;
|
||||||
valueInput: HTMLInputElement,
|
valueInput: HTMLInputElement;
|
||||||
fileInput: HTMLInputElement,
|
fileInput: HTMLInputElement;
|
||||||
fileBlob: fileBlob | null
|
fileBlob: fileBlob | null;
|
||||||
}[] = [];
|
}[] = [];
|
||||||
|
|
||||||
const inputStyle = 'flex: 1; height: 2.5rem; padding: 0.5rem; border: 1px solid #ccc; border-radius: 0.375rem;';
|
const inputStyle = 'flex: 1; height: 2.5rem; padding: 0.5rem; border: 1px solid #ccc; border-radius: 0.375rem;';
|
||||||
@ -65,7 +65,7 @@ export function createKeyValueSection(title: string, id: string, isRoleSection =
|
|||||||
roleName.placeholder = 'Role name';
|
roleName.placeholder = 'Role name';
|
||||||
members.placeholder = 'members';
|
members.placeholder = 'members';
|
||||||
storages.placeholder = 'storages';
|
storages.placeholder = 'storages';
|
||||||
[roleName, members, storages].forEach(input => {
|
[roleName, members, storages].forEach((input) => {
|
||||||
input.type = 'text';
|
input.type = 'text';
|
||||||
input.style.cssText = inputStyle;
|
input.style.cssText = inputStyle;
|
||||||
});
|
});
|
||||||
@ -76,7 +76,7 @@ export function createKeyValueSection(title: string, id: string, isRoleSection =
|
|||||||
|
|
||||||
const rules: ValidationRule[] = [];
|
const rules: ValidationRule[] = [];
|
||||||
ruleButton.onclick = () => {
|
ruleButton.onclick = () => {
|
||||||
showValidationRuleModal(rule => {
|
showValidationRuleModal((rule) => {
|
||||||
rules.push(rule);
|
rules.push(rule);
|
||||||
ruleButton.textContent = `Rules (${rules.length})`;
|
ruleButton.textContent = `Rules (${rules.length})`;
|
||||||
});
|
});
|
||||||
@ -122,13 +122,13 @@ export function createKeyValueSection(title: string, id: string, isRoleSection =
|
|||||||
keyInput,
|
keyInput,
|
||||||
valueInput,
|
valueInput,
|
||||||
fileInput,
|
fileInput,
|
||||||
fileBlob: null as fileBlob | null
|
fileBlob: null as fileBlob | null,
|
||||||
};
|
};
|
||||||
nonRoleRowStates.push(rowState);
|
nonRoleRowStates.push(rowState);
|
||||||
|
|
||||||
keyInput.placeholder = 'Key';
|
keyInput.placeholder = 'Key';
|
||||||
valueInput.placeholder = 'Value';
|
valueInput.placeholder = 'Value';
|
||||||
[keyInput, valueInput].forEach(input => {
|
[keyInput, valueInput].forEach((input) => {
|
||||||
input.type = 'text';
|
input.type = 'text';
|
||||||
input.style.cssText = inputStyle;
|
input.style.cssText = inputStyle;
|
||||||
});
|
});
|
||||||
@ -148,7 +148,7 @@ export function createKeyValueSection(title: string, id: string, isRoleSection =
|
|||||||
|
|
||||||
const updateDeleteButtons = () => {
|
const updateDeleteButtons = () => {
|
||||||
const rows = Array.from(rowContainer.children);
|
const rows = Array.from(rowContainer.children);
|
||||||
rows.forEach(row => {
|
rows.forEach((row) => {
|
||||||
const btn = row.querySelector('button:last-child') as HTMLButtonElement;
|
const btn = row.querySelector('button:last-child') as HTMLButtonElement;
|
||||||
if (rows.length === 1) {
|
if (rows.length === 1) {
|
||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
@ -172,9 +172,15 @@ export function createKeyValueSection(title: string, id: string, isRoleSection =
|
|||||||
const key = row.roleNameInput.value.trim();
|
const key = row.roleNameInput.value.trim();
|
||||||
if (!key) continue;
|
if (!key) continue;
|
||||||
data[key] = {
|
data[key] = {
|
||||||
members: row.membersInput.value.split(',').map(x => x.trim()).filter(Boolean),
|
members: row.membersInput.value
|
||||||
storages: row.storagesInput.value.split(',').map(x => x.trim()).filter(Boolean),
|
.split(',')
|
||||||
validation_rules: row.validationRules
|
.map((x) => x.trim())
|
||||||
|
.filter(Boolean),
|
||||||
|
storages: row.storagesInput.value
|
||||||
|
.split(',')
|
||||||
|
.map((x) => x.trim())
|
||||||
|
.filter(Boolean),
|
||||||
|
validation_rules: row.validationRules,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return data;
|
return data;
|
||||||
@ -191,6 +197,6 @@ export function createKeyValueSection(title: string, id: string, isRoleSection =
|
|||||||
}
|
}
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@ -63,8 +63,8 @@ export async function getProcessCreation(container: HTMLElement) {
|
|||||||
if (!encryptedData) continue;
|
if (!encryptedData) continue;
|
||||||
const filename = `${label}-${hash.slice(0, 8)}.bin`;
|
const filename = `${label}-${hash.slice(0, 8)}.bin`;
|
||||||
|
|
||||||
const blob = new Blob([encryptedData], { type: "application/octet-stream" });
|
const blob = new Blob([encryptedData], { type: 'application/octet-stream' });
|
||||||
const link = document.createElement("a");
|
const link = document.createElement('a');
|
||||||
link.href = URL.createObjectURL(blob);
|
link.href = URL.createObjectURL(blob);
|
||||||
link.download = filename;
|
link.download = filename;
|
||||||
link.click();
|
link.click();
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
export function createProcessTab(container: HTMLElement, processes: { name: string, publicData: Record<string, any> }[]): HTMLElement {
|
export function createProcessTab(container: HTMLElement, processes: { name: string; publicData: Record<string, any> }[]): HTMLElement {
|
||||||
container.id = 'process-tab';
|
container.id = 'process-tab';
|
||||||
container.style.display = 'block';
|
container.style.display = 'block';
|
||||||
container.style.cssText = 'padding: 1.5rem;';
|
container.style.cssText = 'padding: 1.5rem;';
|
||||||
@ -8,7 +8,7 @@ export function createProcessTab(container: HTMLElement, processes: { name: stri
|
|||||||
title.style.cssText = 'font-size: 1.5rem; font-weight: bold; margin-bottom: 1rem;';
|
title.style.cssText = 'font-size: 1.5rem; font-weight: bold; margin-bottom: 1rem;';
|
||||||
container.appendChild(title);
|
container.appendChild(title);
|
||||||
|
|
||||||
processes.forEach(proc => {
|
processes.forEach((proc) => {
|
||||||
const card = document.createElement('div');
|
const card = document.createElement('div');
|
||||||
card.style.cssText = 'margin-bottom: 1rem; padding: 1rem; border: 1px solid #ddd; border-radius: 0.5rem; background: #fff;';
|
card.style.cssText = 'margin-bottom: 1rem; padding: 1rem; border: 1px solid #ddd; border-radius: 0.5rem; background: #fff;';
|
||||||
|
|
||||||
|
168
src/router.ts
168
src/router.ts
@ -139,11 +139,11 @@ export async function registerAllListeners() {
|
|||||||
{
|
{
|
||||||
type: MessageType.ERROR,
|
type: MessageType.ERROR,
|
||||||
error: errorMsg,
|
error: errorMsg,
|
||||||
messageId
|
messageId,
|
||||||
},
|
},
|
||||||
origin
|
origin,
|
||||||
);
|
);
|
||||||
}
|
};
|
||||||
|
|
||||||
// --- Handler functions ---
|
// --- Handler functions ---
|
||||||
const handleRequestLink = async (event: MessageEvent) => {
|
const handleRequestLink = async (event: MessageEvent) => {
|
||||||
@ -155,13 +155,14 @@ export async function registerAllListeners() {
|
|||||||
type: MessageType.LINK_ACCEPTED,
|
type: MessageType.LINK_ACCEPTED,
|
||||||
accessToken: 'e2e-access',
|
accessToken: 'e2e-access',
|
||||||
refreshToken: 'e2e-refresh',
|
refreshToken: 'e2e-refresh',
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
};
|
};
|
||||||
window.parent.postMessage(acceptedMsg, event.origin);
|
window.parent.postMessage(acceptedMsg, event.origin);
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
const modalService = await ModalService.getInstance();
|
const modalService = await ModalService.getInstance();
|
||||||
const result = await modalService.showConfirmationModal({
|
const result = await modalService.showConfirmationModal(
|
||||||
|
{
|
||||||
title: 'Confirmation de liaison',
|
title: 'Confirmation de liaison',
|
||||||
content: `
|
content: `
|
||||||
<div class="modal-confirmation">
|
<div class="modal-confirmation">
|
||||||
@ -172,8 +173,10 @@ export async function registerAllListeners() {
|
|||||||
</div>
|
</div>
|
||||||
`,
|
`,
|
||||||
confirmText: 'Ajouter un service',
|
confirmText: 'Ajouter un service',
|
||||||
cancelText: 'Annuler'
|
cancelText: 'Annuler',
|
||||||
}, true);
|
},
|
||||||
|
true,
|
||||||
|
);
|
||||||
if (!result) {
|
if (!result) {
|
||||||
const errorMsg = 'Failed to pair device: User refused to link';
|
const errorMsg = 'Failed to pair device: User refused to link';
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
@ -186,17 +189,14 @@ export async function registerAllListeners() {
|
|||||||
type: MessageType.LINK_ACCEPTED,
|
type: MessageType.LINK_ACCEPTED,
|
||||||
accessToken: tokens.accessToken,
|
accessToken: tokens.accessToken,
|
||||||
refreshToken: tokens.refreshToken,
|
refreshToken: tokens.refreshToken,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
};
|
};
|
||||||
window.parent.postMessage(
|
window.parent.postMessage(acceptedMsg, event.origin);
|
||||||
acceptedMsg,
|
|
||||||
event.origin
|
|
||||||
);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMsg = `Failed to generate tokens: ${error}`;
|
const errorMsg = `Failed to generate tokens: ${error}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleCreatePairing = async (event: MessageEvent) => {
|
const handleCreatePairing = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== MessageType.CREATE_PAIRING) {
|
if (event.data.type !== MessageType.CREATE_PAIRING) {
|
||||||
@ -230,14 +230,14 @@ export async function registerAllListeners() {
|
|||||||
const successMsg = {
|
const successMsg = {
|
||||||
type: MessageType.PAIRING_CREATED,
|
type: MessageType.PAIRING_CREATED,
|
||||||
pairingId,
|
pairingId,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
};
|
};
|
||||||
window.parent.postMessage(successMsg, event.origin);
|
window.parent.postMessage(successMsg, event.origin);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = `Failed to create pairing process: ${e}`;
|
const errorMsg = `Failed to create pairing process: ${e}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleGetMyProcesses = async (event: MessageEvent) => {
|
const handleGetMyProcesses = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== MessageType.GET_MY_PROCESSES) {
|
if (event.data.type !== MessageType.GET_MY_PROCESSES) {
|
||||||
@ -263,15 +263,15 @@ export async function registerAllListeners() {
|
|||||||
{
|
{
|
||||||
type: MessageType.GET_MY_PROCESSES,
|
type: MessageType.GET_MY_PROCESSES,
|
||||||
myProcesses,
|
myProcesses,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
},
|
},
|
||||||
event.origin
|
event.origin,
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = `Failed to get processes: ${e}`;
|
const errorMsg = `Failed to get processes: ${e}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleGetProcesses = async (event: MessageEvent) => {
|
const handleGetProcesses = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== MessageType.GET_PROCESSES) {
|
if (event.data.type !== MessageType.GET_PROCESSES) {
|
||||||
@ -300,15 +300,15 @@ export async function registerAllListeners() {
|
|||||||
{
|
{
|
||||||
type: MessageType.PROCESSES_RETRIEVED,
|
type: MessageType.PROCESSES_RETRIEVED,
|
||||||
processes,
|
processes,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
},
|
},
|
||||||
event.origin
|
event.origin,
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = `Failed to get processes: ${e}`;
|
const errorMsg = `Failed to get processes: ${e}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
/// We got a state for some process and return as many clear attributes as we can
|
/// We got a state for some process and return as many clear attributes as we can
|
||||||
const handleDecryptState = async (event: MessageEvent) => {
|
const handleDecryptState = async (event: MessageEvent) => {
|
||||||
@ -333,7 +333,7 @@ export async function registerAllListeners() {
|
|||||||
// Retrieve the state for the process
|
// Retrieve the state for the process
|
||||||
const process = await services.getProcess(processId);
|
const process = await services.getProcess(processId);
|
||||||
if (!process) {
|
if (!process) {
|
||||||
throw new Error('Can\'t find process');
|
throw new Error("Can't find process");
|
||||||
}
|
}
|
||||||
const state = services.getStateFromId(process, stateId);
|
const state = services.getStateFromId(process, stateId);
|
||||||
|
|
||||||
@ -357,15 +357,15 @@ export async function registerAllListeners() {
|
|||||||
{
|
{
|
||||||
type: MessageType.DATA_RETRIEVED,
|
type: MessageType.DATA_RETRIEVED,
|
||||||
data: res,
|
data: res,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
},
|
},
|
||||||
event.origin
|
event.origin,
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = `Failed to retrieve data: ${e}`;
|
const errorMsg = `Failed to retrieve data: ${e}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleValidateToken = async (event: MessageEvent) => {
|
const handleValidateToken = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== MessageType.VALIDATE_TOKEN) {
|
if (event.data.type !== MessageType.VALIDATE_TOKEN) {
|
||||||
@ -378,25 +378,31 @@ export async function registerAllListeners() {
|
|||||||
errorResponse('Failed to validate token: missing access, refresh token or both', event.origin, event.data.messageId);
|
errorResponse('Failed to validate token: missing access, refresh token or both', event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
if (isE2E) {
|
if (isE2E) {
|
||||||
window.parent.postMessage({
|
window.parent.postMessage(
|
||||||
|
{
|
||||||
type: MessageType.VALIDATE_TOKEN,
|
type: MessageType.VALIDATE_TOKEN,
|
||||||
accessToken,
|
accessToken,
|
||||||
refreshToken,
|
refreshToken,
|
||||||
isValid: true,
|
isValid: true,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
}, event.origin);
|
},
|
||||||
|
event.origin,
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const isValid = await tokenService.validateToken(accessToken, event.origin);
|
const isValid = await tokenService.validateToken(accessToken, event.origin);
|
||||||
|
|
||||||
window.parent.postMessage({
|
window.parent.postMessage(
|
||||||
|
{
|
||||||
type: MessageType.VALIDATE_TOKEN,
|
type: MessageType.VALIDATE_TOKEN,
|
||||||
accessToken,
|
accessToken,
|
||||||
refreshToken,
|
refreshToken,
|
||||||
isValid,
|
isValid,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
}, event.origin);
|
},
|
||||||
|
event.origin,
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleRenewToken = async (event: MessageEvent) => {
|
const handleRenewToken = async (event: MessageEvent) => {
|
||||||
@ -411,12 +417,15 @@ export async function registerAllListeners() {
|
|||||||
throw new Error('No refresh token provided');
|
throw new Error('No refresh token provided');
|
||||||
}
|
}
|
||||||
if (isE2E) {
|
if (isE2E) {
|
||||||
window.parent.postMessage({
|
window.parent.postMessage(
|
||||||
|
{
|
||||||
type: MessageType.RENEW_TOKEN,
|
type: MessageType.RENEW_TOKEN,
|
||||||
accessToken: 'e2e-access-2',
|
accessToken: 'e2e-access-2',
|
||||||
refreshToken,
|
refreshToken,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
}, event.origin);
|
},
|
||||||
|
event.origin,
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -426,17 +435,20 @@ export async function registerAllListeners() {
|
|||||||
throw new Error('Failed to refresh token');
|
throw new Error('Failed to refresh token');
|
||||||
}
|
}
|
||||||
|
|
||||||
window.parent.postMessage({
|
window.parent.postMessage(
|
||||||
|
{
|
||||||
type: MessageType.RENEW_TOKEN,
|
type: MessageType.RENEW_TOKEN,
|
||||||
accessToken: newAccessToken,
|
accessToken: newAccessToken,
|
||||||
refreshToken,
|
refreshToken,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
}, event.origin);
|
},
|
||||||
|
event.origin,
|
||||||
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMsg = `Failed to renew token: ${error}`;
|
const errorMsg = `Failed to renew token: ${error}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleGetPairingId = async (event: MessageEvent) => {
|
const handleGetPairingId = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== MessageType.GET_PAIRING_ID) return;
|
if (event.data.type !== MessageType.GET_PAIRING_ID) return;
|
||||||
@ -460,15 +472,15 @@ export async function registerAllListeners() {
|
|||||||
{
|
{
|
||||||
type: MessageType.GET_PAIRING_ID,
|
type: MessageType.GET_PAIRING_ID,
|
||||||
userPairingId,
|
userPairingId,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
},
|
},
|
||||||
event.origin
|
event.origin,
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = `Failed to get pairing id: ${e}`;
|
const errorMsg = `Failed to get pairing id: ${e}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleCreateProcess = async (event: MessageEvent) => {
|
const handleCreateProcess = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== MessageType.CREATE_PROCESS) return;
|
if (event.data.type !== MessageType.CREATE_PROCESS) return;
|
||||||
@ -483,11 +495,14 @@ export async function registerAllListeners() {
|
|||||||
const { processData, privateFields, roles, accessToken } = event.data;
|
const { processData, privateFields, roles, accessToken } = event.data;
|
||||||
|
|
||||||
if (isE2E) {
|
if (isE2E) {
|
||||||
window.parent.postMessage({
|
window.parent.postMessage(
|
||||||
|
{
|
||||||
type: MessageType.PROCESS_CREATED,
|
type: MessageType.PROCESS_CREATED,
|
||||||
processCreated: { processId: 'e2e-process', process: {}, processData },
|
processCreated: { processId: 'e2e-process', process: {}, processData },
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
}, event.origin);
|
},
|
||||||
|
event.origin,
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -507,16 +522,19 @@ export async function registerAllListeners() {
|
|||||||
|
|
||||||
const res = { processId, process, processData };
|
const res = { processId, process, processData };
|
||||||
|
|
||||||
window.parent.postMessage({
|
window.parent.postMessage(
|
||||||
|
{
|
||||||
type: MessageType.PROCESS_CREATED,
|
type: MessageType.PROCESS_CREATED,
|
||||||
processCreated: res,
|
processCreated: res,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
}, event.origin);
|
},
|
||||||
|
event.origin,
|
||||||
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = `Failed to create process: ${e}`;
|
const errorMsg = `Failed to create process: ${e}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleNotifyUpdate = async (event: MessageEvent) => {
|
const handleNotifyUpdate = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== MessageType.NOTIFY_UPDATE) return;
|
if (event.data.type !== MessageType.NOTIFY_UPDATE) return;
|
||||||
@ -544,15 +562,15 @@ export async function registerAllListeners() {
|
|||||||
window.parent.postMessage(
|
window.parent.postMessage(
|
||||||
{
|
{
|
||||||
type: MessageType.UPDATE_NOTIFIED,
|
type: MessageType.UPDATE_NOTIFIED,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
},
|
},
|
||||||
event.origin
|
event.origin,
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = `Failed to notify update for process: ${e}`;
|
const errorMsg = `Failed to notify update for process: ${e}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleValidateState = async (event: MessageEvent) => {
|
const handleValidateState = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== MessageType.VALIDATE_STATE) return;
|
if (event.data.type !== MessageType.VALIDATE_STATE) return;
|
||||||
@ -577,15 +595,15 @@ export async function registerAllListeners() {
|
|||||||
{
|
{
|
||||||
type: MessageType.STATE_VALIDATED,
|
type: MessageType.STATE_VALIDATED,
|
||||||
validatedProcess: res.updated_process,
|
validatedProcess: res.updated_process,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
},
|
},
|
||||||
event.origin
|
event.origin,
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = `Failed to validate process: ${e}`;
|
const errorMsg = `Failed to validate process: ${e}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleUpdateProcess = async (event: MessageEvent) => {
|
const handleUpdateProcess = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== MessageType.UPDATE_PROCESS) return;
|
if (event.data.type !== MessageType.UPDATE_PROCESS) return;
|
||||||
@ -626,15 +644,15 @@ export async function registerAllListeners() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Wait a couple seconds
|
// Wait a couple seconds
|
||||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||||
lastState = services.getLastCommitedState(process);
|
lastState = services.getLastCommitedState(process);
|
||||||
if (!lastState) {
|
if (!lastState) {
|
||||||
throw new Error('Process doesn\'t have a commited state yet');
|
throw new Error("Process doesn't have a commited state yet");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const lastStateIndex = services.getLastCommitedStateIndex(process);
|
const lastStateIndex = services.getLastCommitedStateIndex(process);
|
||||||
if (lastStateIndex === null) {
|
if (lastStateIndex === null) {
|
||||||
throw new Error('Process doesn\'t have a commited state yet');
|
throw new Error("Process doesn't have a commited state yet");
|
||||||
} // Shouldn't happen
|
} // Shouldn't happen
|
||||||
|
|
||||||
const privateData: Record<string, any> = {};
|
const privateData: Record<string, any> = {};
|
||||||
@ -686,15 +704,15 @@ export async function registerAllListeners() {
|
|||||||
{
|
{
|
||||||
type: MessageType.PROCESS_UPDATED,
|
type: MessageType.PROCESS_UPDATED,
|
||||||
updatedProcess: res.updated_process,
|
updatedProcess: res.updated_process,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
},
|
},
|
||||||
event.origin
|
event.origin,
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = `Failed to update process: ${e}`;
|
const errorMsg = `Failed to update process: ${e}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleDecodePublicData = async (event: MessageEvent) => {
|
const handleDecodePublicData = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== MessageType.DECODE_PUBLIC_DATA) return;
|
if (event.data.type !== MessageType.DECODE_PUBLIC_DATA) return;
|
||||||
@ -718,15 +736,15 @@ export async function registerAllListeners() {
|
|||||||
{
|
{
|
||||||
type: MessageType.PUBLIC_DATA_DECODED,
|
type: MessageType.PUBLIC_DATA_DECODED,
|
||||||
decodedData,
|
decodedData,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
},
|
},
|
||||||
event.origin
|
event.origin,
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = `Failed to decode data: ${e}`;
|
const errorMsg = `Failed to decode data: ${e}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleHashValue = async (event: MessageEvent) => {
|
const handleHashValue = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== MessageType.HASH_VALUE) return;
|
if (event.data.type !== MessageType.HASH_VALUE) return;
|
||||||
@ -746,15 +764,15 @@ export async function registerAllListeners() {
|
|||||||
{
|
{
|
||||||
type: MessageType.VALUE_HASHED,
|
type: MessageType.VALUE_HASHED,
|
||||||
hash,
|
hash,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
},
|
},
|
||||||
event.origin
|
event.origin,
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = `Failed to hash value: ${e}`;
|
const errorMsg = `Failed to hash value: ${e}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleGetMerkleProof = async (event: MessageEvent) => {
|
const handleGetMerkleProof = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== MessageType.GET_MERKLE_PROOF) return;
|
if (event.data.type !== MessageType.GET_MERKLE_PROOF) return;
|
||||||
@ -772,15 +790,15 @@ export async function registerAllListeners() {
|
|||||||
{
|
{
|
||||||
type: MessageType.MERKLE_PROOF_RETRIEVED,
|
type: MessageType.MERKLE_PROOF_RETRIEVED,
|
||||||
proof,
|
proof,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
},
|
},
|
||||||
event.origin
|
event.origin,
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = `Failed to get merkle proof: ${e}`;
|
const errorMsg = `Failed to get merkle proof: ${e}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleValidateMerkleProof = async (event: MessageEvent) => {
|
const handleValidateMerkleProof = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== MessageType.VALIDATE_MERKLE_PROOF) return;
|
if (event.data.type !== MessageType.VALIDATE_MERKLE_PROOF) return;
|
||||||
@ -807,15 +825,15 @@ export async function registerAllListeners() {
|
|||||||
{
|
{
|
||||||
type: MessageType.MERKLE_PROOF_VALIDATED,
|
type: MessageType.MERKLE_PROOF_VALIDATED,
|
||||||
isValid: res,
|
isValid: res,
|
||||||
messageId: event.data.messageId
|
messageId: event.data.messageId,
|
||||||
},
|
},
|
||||||
event.origin
|
event.origin,
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = `Failed to get merkle proof: ${e}`;
|
const errorMsg = `Failed to get merkle proof: ${e}`;
|
||||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
window.removeEventListener('message', handleMessage);
|
window.removeEventListener('message', handleMessage);
|
||||||
window.addEventListener('message', handleMessage);
|
window.addEventListener('message', handleMessage);
|
||||||
@ -915,8 +933,8 @@ async function injectHeader() {
|
|||||||
|
|
||||||
(window as any).navigate = navigate;
|
(window as any).navigate = navigate;
|
||||||
|
|
||||||
document.addEventListener('navigate', ((e: Event) => {
|
document.addEventListener('navigate', (e: Event) => {
|
||||||
const event = e as CustomEvent<{page: string, processId?: string}>;
|
const event = e as CustomEvent<{ page: string; processId?: string }>;
|
||||||
if (event.detail.page === 'chat') {
|
if (event.detail.page === 'chat') {
|
||||||
const container = document.querySelector('.container');
|
const container = document.querySelector('.container');
|
||||||
if (container) container.innerHTML = '';
|
if (container) container.innerHTML = '';
|
||||||
@ -928,4 +946,4 @@ document.addEventListener('navigate', ((e: Event) => {
|
|||||||
chatElement.setAttribute('process-id', event.detail.processId || '');
|
chatElement.setAttribute('process-id', event.detail.processId || '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}));
|
});
|
||||||
|
@ -139,7 +139,7 @@ async function getAllProcesses() {
|
|||||||
reject(request.error);
|
reject(request.error);
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
};
|
}
|
||||||
|
|
||||||
async function getProcesses(processIds) {
|
async function getProcesses(processIds) {
|
||||||
if (!processIds || processIds.length === 0) {
|
if (!processIds || processIds.length === 0) {
|
||||||
@ -166,7 +166,7 @@ async function getProcesses(processIds) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const results = await Promise.all(requests);
|
const results = await Promise.all(requests);
|
||||||
return results.filter(result => result !== undefined);
|
return results.filter((result) => result !== undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getAllDiffsNeedValidation() {
|
async function getAllDiffsNeedValidation() {
|
||||||
@ -204,11 +204,11 @@ async function getAllDiffsNeedValidation() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const results = Object.values(processMap).map((entry) => {
|
const results = Object.values(processMap).map((entry) => {
|
||||||
const diffs = []
|
const diffs = [];
|
||||||
for (const state of entry.process) {
|
for (const state of entry.process) {
|
||||||
const filteredDiff = entry.diffs.filter(diff => diff.new_state_merkle_root === state.merkle_root);
|
const filteredDiff = entry.diffs.filter((diff) => diff.new_state_merkle_root === state.merkle_root);
|
||||||
if (filteredDiff && filteredDiff.length) {
|
if (filteredDiff && filteredDiff.length) {
|
||||||
diffs.push(filteredDiff)
|
diffs.push(filteredDiff);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
@ -265,7 +265,7 @@ async function addDiff(processId, stateId, hash, roles, field) {
|
|||||||
new_value: null,
|
new_value: null,
|
||||||
notify_user: false,
|
notify_user: false,
|
||||||
need_validation: false,
|
need_validation: false,
|
||||||
validation_status: 'None'
|
validation_status: 'None',
|
||||||
};
|
};
|
||||||
|
|
||||||
const insertResult = await new Promise((resolve, reject) => {
|
const insertResult = await new Promise((resolve, reject) => {
|
||||||
|
@ -128,7 +128,7 @@ export class Database {
|
|||||||
} else {
|
} else {
|
||||||
// More than one existing worker: unregister them all and register a new one.
|
// More than one existing worker: unregister them all and register a new one.
|
||||||
console.log('Multiple Service Worker(s) detected. Unregistering all...');
|
console.log('Multiple Service Worker(s) detected. Unregistering all...');
|
||||||
await Promise.all(registrations.map(reg => reg.unregister()));
|
await Promise.all(registrations.map((reg) => reg.unregister()));
|
||||||
console.log('All previous Service Workers unregistered.');
|
console.log('All previous Service Workers unregistered.');
|
||||||
this.serviceWorkerRegistration = await navigator.serviceWorker.register(path, { type: 'module' });
|
this.serviceWorkerRegistration = await navigator.serviceWorker.register(path, { type: 'module' });
|
||||||
console.log('Service Worker registered with scope:', this.serviceWorkerRegistration.scope);
|
console.log('Service Worker registered with scope:', this.serviceWorkerRegistration.scope);
|
||||||
@ -217,15 +217,17 @@ export class Database {
|
|||||||
const valueBytes = await service.fetchValueFromStorage(hash);
|
const valueBytes = await service.fetchValueFromStorage(hash);
|
||||||
if (valueBytes) {
|
if (valueBytes) {
|
||||||
// Save data to db
|
// Save data to db
|
||||||
const blob = new Blob([valueBytes], {type: "application/octet-stream"});
|
const blob = new Blob([valueBytes], { type: 'application/octet-stream' });
|
||||||
await service.saveBlobToDb(hash, blob);
|
await service.saveBlobToDb(hash, blob);
|
||||||
document.dispatchEvent(new CustomEvent('newDataReceived', {
|
document.dispatchEvent(
|
||||||
|
new CustomEvent('newDataReceived', {
|
||||||
detail: {
|
detail: {
|
||||||
processId,
|
processId,
|
||||||
stateId,
|
stateId,
|
||||||
hash,
|
hash,
|
||||||
}
|
},
|
||||||
}));
|
}),
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
// We first request the data from managers
|
// We first request the data from managers
|
||||||
console.log('Request data from managers of the process');
|
console.log('Request data from managers of the process');
|
||||||
@ -256,7 +258,7 @@ export class Database {
|
|||||||
const valueBytes = await service.fetchValueFromStorage(hash);
|
const valueBytes = await service.fetchValueFromStorage(hash);
|
||||||
if (valueBytes) {
|
if (valueBytes) {
|
||||||
// Save data to db
|
// Save data to db
|
||||||
const blob = new Blob([valueBytes], {type: "application/octet-stream"});
|
const blob = new Blob([valueBytes], { type: 'application/octet-stream' });
|
||||||
await service.saveBlobToDb(hash, blob);
|
await service.saveBlobToDb(hash, blob);
|
||||||
} else {
|
} else {
|
||||||
// We first request the data from managers
|
// We first request the data from managers
|
||||||
@ -440,7 +442,7 @@ export class Database {
|
|||||||
const getAllRequest = index.getAll(request);
|
const getAllRequest = index.getAll(request);
|
||||||
getAllRequest.onsuccess = () => {
|
getAllRequest.onsuccess = () => {
|
||||||
const allItems = getAllRequest.result;
|
const allItems = getAllRequest.result;
|
||||||
const filtered = allItems.filter(item => item.state_id === request);
|
const filtered = allItems.filter((item) => item.state_id === request);
|
||||||
resolve(filtered);
|
resolve(filtered);
|
||||||
};
|
};
|
||||||
getAllRequest.onerror = () => reject(getAllRequest.error);
|
getAllRequest.onerror = () => reject(getAllRequest.error);
|
||||||
|
@ -90,7 +90,7 @@ export default class ModalService {
|
|||||||
const container = document.querySelector('#containerId');
|
const container = document.querySelector('#containerId');
|
||||||
if (container) {
|
if (container) {
|
||||||
let html = await fetch('/src/components/validation-modal/validation-modal.html').then((res) => res.text());
|
let html = await fetch('/src/components/validation-modal/validation-modal.html').then((res) => res.text());
|
||||||
html = interpolate(html, {processId: processDiff.processId})
|
html = interpolate(html, { processId: processDiff.processId });
|
||||||
container.innerHTML += html;
|
container.innerHTML += html;
|
||||||
|
|
||||||
// Dynamically load the header JS
|
// Dynamically load the header JS
|
||||||
@ -103,7 +103,7 @@ export default class ModalService {
|
|||||||
css.id = 'validation-modal-css';
|
css.id = 'validation-modal-css';
|
||||||
css.innerText = validationModalStyle;
|
css.innerText = validationModalStyle;
|
||||||
document.head.appendChild(css);
|
document.head.appendChild(css);
|
||||||
initValidationModal(processDiff)
|
initValidationModal(processDiff);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -129,7 +129,7 @@ export default class ModalService {
|
|||||||
throw new Error('Must have exactly 1 member');
|
throw new Error('Must have exactly 1 member');
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("MEMBER OUTPOINTS:", memberOutPoints);
|
console.log('MEMBER OUTPOINTS:', memberOutPoints);
|
||||||
// We take all the addresses except our own
|
// We take all the addresses except our own
|
||||||
const service = await Services.getInstance();
|
const service = await Services.getInstance();
|
||||||
const localAddress = service.getDeviceAddress();
|
const localAddress = service.getDeviceAddress();
|
||||||
@ -158,11 +158,11 @@ export default class ModalService {
|
|||||||
if (members[0].sp_addresses.length === 1) {
|
if (members[0].sp_addresses.length === 1) {
|
||||||
await this.injectCreationModal(members);
|
await this.injectCreationModal(members);
|
||||||
this.modal = document.getElementById('creation-modal');
|
this.modal = document.getElementById('creation-modal');
|
||||||
console.log("LENGTH:", members[0].sp_addresses.length);
|
console.log('LENGTH:', members[0].sp_addresses.length);
|
||||||
} else {
|
} else {
|
||||||
await this.injectModal(members);
|
await this.injectModal(members);
|
||||||
this.modal = document.getElementById('modal');
|
this.modal = document.getElementById('modal');
|
||||||
console.log("LENGTH:", members[0].sp_addresses.length);
|
console.log('LENGTH:', members[0].sp_addresses.length);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.modal) this.modal.style.display = 'flex';
|
if (this.modal) this.modal.style.display = 'flex';
|
||||||
|
@ -12,8 +12,8 @@ export const U32_MAX = 4294967295;
|
|||||||
|
|
||||||
const BASEURL = `http://localhost`;
|
const BASEURL = `http://localhost`;
|
||||||
const BOOTSTRAPURL = [`${BASEURL}:8090`];
|
const BOOTSTRAPURL = [`${BASEURL}:8090`];
|
||||||
const STORAGEURL = `${BASEURL}:8081`
|
const STORAGEURL = `${BASEURL}:8081`;
|
||||||
const BLINDBITURL = `${BASEURL}:8000`
|
const BLINDBITURL = `${BASEURL}:8000`;
|
||||||
const DEFAULTAMOUNT = 1000n;
|
const DEFAULTAMOUNT = 1000n;
|
||||||
const EMPTY32BYTES = String('').padStart(64, '0');
|
const EMPTY32BYTES = String('').padStart(64, '0');
|
||||||
|
|
||||||
@ -153,7 +153,7 @@ export default class Services {
|
|||||||
* Print all key/value pairs for debugging.
|
* Print all key/value pairs for debugging.
|
||||||
*/
|
*/
|
||||||
public printAllRelays(): void {
|
public printAllRelays(): void {
|
||||||
console.log("Current relay addresses:");
|
console.log('Current relay addresses:');
|
||||||
for (const [wsurl, spAddress] of Object.entries(this.relayAddresses)) {
|
for (const [wsurl, spAddress] of Object.entries(this.relayAddresses)) {
|
||||||
console.log(`${wsurl} -> ${spAddress}`);
|
console.log(`${wsurl} -> ${spAddress}`);
|
||||||
}
|
}
|
||||||
@ -307,27 +307,18 @@ export default class Services {
|
|||||||
min_sig_member: 1.0,
|
min_sig_member: 1.0,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
storages: [STORAGEURL]
|
storages: [STORAGEURL],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
return this.createProcess(
|
return this.createProcess(privateData, publicData, roles);
|
||||||
privateData,
|
|
||||||
publicData,
|
|
||||||
roles
|
|
||||||
);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new Error(`Creating process failed:, ${e}`);
|
throw new Error(`Creating process failed:, ${e}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private isFileBlob(value: any): value is { type: string, data: Uint8Array } {
|
private isFileBlob(value: any): value is { type: string; data: Uint8Array } {
|
||||||
return (
|
return typeof value === 'object' && value !== null && typeof value.type === 'string' && value.data instanceof Uint8Array;
|
||||||
typeof value === 'object' &&
|
|
||||||
value !== null &&
|
|
||||||
typeof value.type === 'string' &&
|
|
||||||
value.data instanceof Uint8Array
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private splitData(obj: Record<string, any>) {
|
private splitData(obj: Record<string, any>) {
|
||||||
@ -345,11 +336,7 @@ export default class Services {
|
|||||||
return { jsonCompatibleData, binaryData };
|
return { jsonCompatibleData, binaryData };
|
||||||
}
|
}
|
||||||
|
|
||||||
public async createProcess(
|
public async createProcess(privateData: Record<string, any>, publicData: Record<string, any>, roles: Record<string, RoleDefinition>): Promise<ApiReturn> {
|
||||||
privateData: Record<string, any>,
|
|
||||||
publicData: Record<string, any>,
|
|
||||||
roles: Record<string, RoleDefinition>,
|
|
||||||
): Promise<ApiReturn> {
|
|
||||||
let relayAddress = this.getAllRelays()[0]?.spAddress;
|
let relayAddress = this.getAllRelays()[0]?.spAddress;
|
||||||
|
|
||||||
if (!relayAddress || relayAddress === '') {
|
if (!relayAddress || relayAddress === '') {
|
||||||
@ -372,11 +359,11 @@ export default class Services {
|
|||||||
const publicSplitData = this.splitData(publicData);
|
const publicSplitData = this.splitData(publicData);
|
||||||
const encodedPrivateData = {
|
const encodedPrivateData = {
|
||||||
...this.sdkClient.encode_json(privateSplitData.jsonCompatibleData),
|
...this.sdkClient.encode_json(privateSplitData.jsonCompatibleData),
|
||||||
...this.sdkClient.encode_binary(privateSplitData.binaryData)
|
...this.sdkClient.encode_binary(privateSplitData.binaryData),
|
||||||
};
|
};
|
||||||
const encodedPublicData = {
|
const encodedPublicData = {
|
||||||
...this.sdkClient.encode_json(publicSplitData.jsonCompatibleData),
|
...this.sdkClient.encode_json(publicSplitData.jsonCompatibleData),
|
||||||
...this.sdkClient.encode_binary(publicSplitData.binaryData)
|
...this.sdkClient.encode_binary(publicSplitData.binaryData),
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log('encoded data:', encodedPrivateData);
|
console.log('encoded data:', encodedPrivateData);
|
||||||
@ -395,16 +382,9 @@ export default class Services {
|
|||||||
console.log('members:', members);
|
console.log('members:', members);
|
||||||
await this.checkConnections([...members]);
|
await this.checkConnections([...members]);
|
||||||
|
|
||||||
const result = this.sdkClient.create_new_process (
|
const result = this.sdkClient.create_new_process(encodedPrivateData, roles, encodedPublicData, relayAddress, feeRate, this.getAllMembers());
|
||||||
encodedPrivateData,
|
|
||||||
roles,
|
|
||||||
encodedPublicData,
|
|
||||||
relayAddress,
|
|
||||||
feeRate,
|
|
||||||
this.getAllMembers()
|
|
||||||
);
|
|
||||||
|
|
||||||
return(result);
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async updateProcess(process: Process, privateData: Record<string, any>, publicData: Record<string, any>, roles: Record<string, RoleDefinition> | null): Promise<ApiReturn> {
|
public async updateProcess(process: Process, privateData: Record<string, any>, publicData: Record<string, any>, roles: Record<string, RoleDefinition> | null): Promise<ApiReturn> {
|
||||||
@ -418,7 +398,7 @@ export default class Services {
|
|||||||
let members: Set<Member> = new Set();
|
let members: Set<Member> = new Set();
|
||||||
for (const role of Object.values(roles!)) {
|
for (const role of Object.values(roles!)) {
|
||||||
for (const member of role.members) {
|
for (const member of role.members) {
|
||||||
members.add(member)
|
members.add(member);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (members.size === 0) {
|
if (members.size === 0) {
|
||||||
@ -439,11 +419,11 @@ export default class Services {
|
|||||||
const publicSplitData = this.splitData(publicData);
|
const publicSplitData = this.splitData(publicData);
|
||||||
const encodedPrivateData = {
|
const encodedPrivateData = {
|
||||||
...this.sdkClient.encode_json(privateSplitData.jsonCompatibleData),
|
...this.sdkClient.encode_json(privateSplitData.jsonCompatibleData),
|
||||||
...this.sdkClient.encode_binary(privateSplitData.binaryData)
|
...this.sdkClient.encode_binary(privateSplitData.binaryData),
|
||||||
};
|
};
|
||||||
const encodedPublicData = {
|
const encodedPublicData = {
|
||||||
...this.sdkClient.encode_json(publicSplitData.jsonCompatibleData),
|
...this.sdkClient.encode_json(publicSplitData.jsonCompatibleData),
|
||||||
...this.sdkClient.encode_binary(publicSplitData.binaryData)
|
...this.sdkClient.encode_binary(publicSplitData.binaryData),
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
return this.sdkClient.update_process(process, encodedPrivateData, roles, encodedPublicData, this.getAllMembers());
|
return this.sdkClient.update_process(process, encodedPrivateData, roles, encodedPublicData, this.getAllMembers());
|
||||||
@ -544,7 +524,6 @@ export default class Services {
|
|||||||
if (waitingModal) {
|
if (waitingModal) {
|
||||||
this.device2Ready = true;
|
this.device2Ready = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(`Parsed cipher with error: ${e}`);
|
console.error(`Parsed cipher with error: ${e}`);
|
||||||
}
|
}
|
||||||
@ -612,7 +591,7 @@ export default class Services {
|
|||||||
|
|
||||||
if (apiReturn.new_tx_to_send && apiReturn.new_tx_to_send.transaction.length != 0) {
|
if (apiReturn.new_tx_to_send && apiReturn.new_tx_to_send.transaction.length != 0) {
|
||||||
this.sendNewTxMessage(JSON.stringify(apiReturn.new_tx_to_send));
|
this.sendNewTxMessage(JSON.stringify(apiReturn.new_tx_to_send));
|
||||||
await new Promise(r => setTimeout(r, 500));
|
await new Promise((r) => setTimeout(r, 500));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (apiReturn.secrets) {
|
if (apiReturn.secrets) {
|
||||||
@ -789,7 +768,7 @@ export default class Services {
|
|||||||
try {
|
try {
|
||||||
let encodedSpAddressList: number[] = [];
|
let encodedSpAddressList: number[] = [];
|
||||||
if (this.stateId) {
|
if (this.stateId) {
|
||||||
const state = process.states.find(state => state.state_id === this.stateId);
|
const state = process.states.find((state) => state.state_id === this.stateId);
|
||||||
if (state) {
|
if (state) {
|
||||||
encodedSpAddressList = state.public_data['pairedAddresses'];
|
encodedSpAddressList = state.public_data['pairedAddresses'];
|
||||||
}
|
}
|
||||||
@ -858,7 +837,7 @@ export default class Services {
|
|||||||
try {
|
try {
|
||||||
const prevDevice = await this.getDeviceFromDatabase();
|
const prevDevice = await this.getDeviceFromDatabase();
|
||||||
if (prevDevice) {
|
if (prevDevice) {
|
||||||
await db.deleteObject(walletStore, "1");
|
await db.deleteObject(walletStore, '1');
|
||||||
}
|
}
|
||||||
await db.addObject({
|
await db.addObject({
|
||||||
storeName: walletStore,
|
storeName: walletStore,
|
||||||
@ -1256,7 +1235,7 @@ export default class Services {
|
|||||||
let retries = 0;
|
let retries = 0;
|
||||||
|
|
||||||
while ((!hash || !key) && retries < maxRetries) {
|
while ((!hash || !key) && retries < maxRetries) {
|
||||||
await new Promise(resolve => setTimeout(resolve, retryDelay));
|
await new Promise((resolve) => setTimeout(resolve, retryDelay));
|
||||||
// Re-read hash and key after waiting
|
// Re-read hash and key after waiting
|
||||||
hash = state.pcd_commitment[attribute];
|
hash = state.pcd_commitment[attribute];
|
||||||
key = state.keys[attribute];
|
key = state.keys[attribute];
|
||||||
@ -1373,7 +1352,6 @@ export default class Services {
|
|||||||
this.device2Ready = false;
|
this.device2Ready = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Handle the handshake message
|
// Handle the handshake message
|
||||||
public async handleHandshakeMsg(url: string, parsedMsg: any) {
|
public async handleHandshakeMsg(url: string, parsedMsg: any) {
|
||||||
try {
|
try {
|
||||||
@ -1414,7 +1392,9 @@ export default class Services {
|
|||||||
let new_states: string[] = [];
|
let new_states: string[] = [];
|
||||||
let roles: Record<string, RoleDefinition>[] = [];
|
let roles: Record<string, RoleDefinition>[] = [];
|
||||||
for (const state of process.states) {
|
for (const state of process.states) {
|
||||||
if (!state.state_id || state.state_id === EMPTY32BYTES) { continue; }
|
if (!state.state_id || state.state_id === EMPTY32BYTES) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (!this.lookForStateId(existing, state.state_id)) {
|
if (!this.lookForStateId(existing, state.state_id)) {
|
||||||
if (this.rolesContainsUs(state.roles)) {
|
if (this.rolesContainsUs(state.roles)) {
|
||||||
new_states.push(state.state_id);
|
new_states.push(state.state_id);
|
||||||
@ -1462,7 +1442,7 @@ export default class Services {
|
|||||||
|
|
||||||
await this.batchSaveProcessesToDb(toSave);
|
await this.batchSaveProcessesToDb(toSave);
|
||||||
}
|
}
|
||||||
}, 500)
|
}, 500);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Failed to parse init message:', e);
|
console.error('Failed to parse init message:', e);
|
||||||
}
|
}
|
||||||
@ -1515,9 +1495,7 @@ export default class Services {
|
|||||||
* @returns Un tableau contenant tous les membres
|
* @returns Un tableau contenant tous les membres
|
||||||
*/
|
*/
|
||||||
public getAllMembersSorted(): Record<string, Member> {
|
public getAllMembersSorted(): Record<string, Member> {
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(Object.entries(this.membersList).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)));
|
||||||
Object.entries(this.membersList).sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public getAllMembers(): Record<string, Member> {
|
public getAllMembers(): Record<string, Member> {
|
||||||
@ -1533,10 +1511,14 @@ export default class Services {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public compareMembers(memberA: string[], memberB: string[]): boolean {
|
public compareMembers(memberA: string[], memberB: string[]): boolean {
|
||||||
if (!memberA || !memberB) { return false }
|
if (!memberA || !memberB) {
|
||||||
if (memberA.length !== memberB.length) { return false }
|
return false;
|
||||||
|
}
|
||||||
|
if (memberA.length !== memberB.length) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
const res = memberA.every(item => memberB.includes(item)) && memberB.every(item => memberA.includes(item));
|
const res = memberA.every((item) => memberB.includes(item)) && memberB.every((item) => memberA.includes(item));
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
@ -1545,16 +1527,14 @@ export default class Services {
|
|||||||
const content = JSON.parse(response);
|
const content = JSON.parse(response);
|
||||||
const error = content.error;
|
const error = content.error;
|
||||||
const errorMsg = error['GenericError'];
|
const errorMsg = error['GenericError'];
|
||||||
const dontRetry = [
|
const dontRetry = ['State is identical to the previous state', 'Not enough valid proofs', 'Not enough members to validate'];
|
||||||
'State is identical to the previous state',
|
if (dontRetry.includes(errorMsg)) {
|
||||||
'Not enough valid proofs',
|
return;
|
||||||
'Not enough members to validate',
|
}
|
||||||
];
|
|
||||||
if (dontRetry.includes(errorMsg)) { return; }
|
|
||||||
// Wait and retry
|
// Wait and retry
|
||||||
setTimeout(async () => {
|
setTimeout(async () => {
|
||||||
this.sendCommitMessage(JSON.stringify(content));
|
this.sendCommitMessage(JSON.stringify(content));
|
||||||
}, 1000)
|
}, 1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
public getRoles(process: Process): Record<string, RoleDefinition> | null {
|
public getRoles(process: Process): Record<string, RoleDefinition> | null {
|
||||||
@ -1587,8 +1567,11 @@ export default class Services {
|
|||||||
const lastCommitedState = this.getLastCommitedState(process);
|
const lastCommitedState = this.getLastCommitedState(process);
|
||||||
if (lastCommitedState && lastCommitedState.public_data) {
|
if (lastCommitedState && lastCommitedState.public_data) {
|
||||||
const processName = lastCommitedState!.public_data['processName'];
|
const processName = lastCommitedState!.public_data['processName'];
|
||||||
if (processName) { return this.decodeValue(processName) }
|
if (processName) {
|
||||||
else { return null }
|
return this.decodeValue(processName);
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -1630,7 +1613,7 @@ export default class Services {
|
|||||||
this.myProcesses = newMyProcesses; // atomic update
|
this.myProcesses = newMyProcesses; // atomic update
|
||||||
return Array.from(this.myProcesses);
|
return Array.from(this.myProcesses);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Failed to get processes:", e);
|
console.error('Failed to get processes:', e);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1652,12 +1635,12 @@ export default class Services {
|
|||||||
const ab = new ArrayBuffer(uint8Array.length);
|
const ab = new ArrayBuffer(uint8Array.length);
|
||||||
const view = new Uint8Array(ab);
|
const view = new Uint8Array(ab);
|
||||||
view.set(uint8Array);
|
view.set(uint8Array);
|
||||||
return new Blob([ab], { type: "application/octet-stream" });
|
return new Blob([ab], { type: 'application/octet-stream' });
|
||||||
}
|
}
|
||||||
|
|
||||||
public hexToUInt8Array(hexString: string): Uint8Array {
|
public hexToUInt8Array(hexString: string): Uint8Array {
|
||||||
if (hexString.length % 2 !== 0) {
|
if (hexString.length % 2 !== 0) {
|
||||||
throw new Error("Invalid hex string: length must be even");
|
throw new Error('Invalid hex string: length must be even');
|
||||||
}
|
}
|
||||||
const uint8Array = new Uint8Array(hexString.length / 2);
|
const uint8Array = new Uint8Array(hexString.length / 2);
|
||||||
for (let i = 0; i < hexString.length; i += 2) {
|
for (let i = 0; i < hexString.length; i += 2) {
|
||||||
@ -1671,7 +1654,7 @@ export default class Services {
|
|||||||
const buffer = await blob.arrayBuffer();
|
const buffer = await blob.arrayBuffer();
|
||||||
const bytes = new Uint8Array(buffer);
|
const bytes = new Uint8Array(buffer);
|
||||||
return Array.from(bytes)
|
return Array.from(bytes)
|
||||||
.map(byte => byte.toString(16).padStart(2, '0'))
|
.map((byte) => byte.toString(16).padStart(2, '0'))
|
||||||
.join('');
|
.join('');
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1743,7 +1726,9 @@ export default class Services {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public isPairingProcess(roles: Record<string, RoleDefinition>): boolean {
|
public isPairingProcess(roles: Record<string, RoleDefinition>): boolean {
|
||||||
if (Object.keys(roles).length != 1) { return false }
|
if (Object.keys(roles).length != 1) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
const pairingRole = roles['pairing'];
|
const pairingRole = roles['pairing'];
|
||||||
if (pairingRole) {
|
if (pairingRole) {
|
||||||
// For now that's enough, we should probably test more things
|
// For now that's enough, we should probably test more things
|
||||||
@ -1755,7 +1740,7 @@ export default class Services {
|
|||||||
|
|
||||||
public async updateMemberPublicName(process: Process, newName: string): Promise<ApiReturn> {
|
public async updateMemberPublicName(process: Process, newName: string): Promise<ApiReturn> {
|
||||||
const publicData = {
|
const publicData = {
|
||||||
'memberPublicName': newName
|
memberPublicName: newName,
|
||||||
};
|
};
|
||||||
|
|
||||||
return await this.updateProcess(process, {}, publicData, null);
|
return await this.updateProcess(process, {}, publicData, null);
|
||||||
|
@ -13,7 +13,7 @@ export async function storeData(servers: string[], key: string, value: Blob, ttl
|
|||||||
// Send the encrypted ArrayBuffer as the raw request body.
|
// Send the encrypted ArrayBuffer as the raw request body.
|
||||||
const response = await axios.post(url.toString(), value, {
|
const response = await axios.post(url.toString(), value, {
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/octet-stream'
|
'Content-Type': 'application/octet-stream',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
console.log('Data stored successfully:', key);
|
console.log('Data stored successfully:', key);
|
||||||
@ -37,7 +37,7 @@ export async function retrieveData(servers: string[], key: string): Promise<Arra
|
|||||||
try {
|
try {
|
||||||
// When fetching the data from the server:
|
// When fetching the data from the server:
|
||||||
const response = await axios.get(`${server}/retrieve/${key}`, {
|
const response = await axios.get(`${server}/retrieve/${key}`, {
|
||||||
responseType: 'arraybuffer'
|
responseType: 'arraybuffer',
|
||||||
});
|
});
|
||||||
if (response.status !== 200) {
|
if (response.status !== 200) {
|
||||||
console.error('Received response status', response.status);
|
console.error('Received response status', response.status);
|
||||||
@ -49,7 +49,7 @@ export async function retrieveData(servers: string[], key: string): Promise<Arra
|
|||||||
console.error('Error retrieving data:', error);
|
console.error('Error retrieving data:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TestResponse {
|
interface TestResponse {
|
||||||
|
@ -38,17 +38,9 @@ export default class TokenService {
|
|||||||
async generateSessionToken(origin: string): Promise<TokenPair> {
|
async generateSessionToken(origin: string): Promise<TokenPair> {
|
||||||
const secret = new Uint8Array(this.encoder.encode(this.SECRET_KEY));
|
const secret = new Uint8Array(this.encoder.encode(this.SECRET_KEY));
|
||||||
|
|
||||||
const accessToken = await new jose.SignJWT({ origin, type: 'access' })
|
const accessToken = await new jose.SignJWT({ origin, type: 'access' }).setProtectedHeader({ alg: 'HS256' }).setIssuedAt().setExpirationTime(this.ACCESS_TOKEN_EXPIRATION).sign(secret);
|
||||||
.setProtectedHeader({ alg: 'HS256' })
|
|
||||||
.setIssuedAt()
|
|
||||||
.setExpirationTime(this.ACCESS_TOKEN_EXPIRATION)
|
|
||||||
.sign(secret);
|
|
||||||
|
|
||||||
const refreshToken = await new jose.SignJWT({ origin, type: 'refresh' })
|
const refreshToken = await new jose.SignJWT({ origin, type: 'refresh' }).setProtectedHeader({ alg: 'HS256' }).setIssuedAt().setExpirationTime(this.REFRESH_TOKEN_EXPIRATION).sign(secret);
|
||||||
.setProtectedHeader({ alg: 'HS256' })
|
|
||||||
.setIssuedAt()
|
|
||||||
.setExpirationTime(this.REFRESH_TOKEN_EXPIRATION)
|
|
||||||
.sign(secret);
|
|
||||||
|
|
||||||
return { accessToken, refreshToken };
|
return { accessToken, refreshToken };
|
||||||
}
|
}
|
||||||
@ -86,11 +78,7 @@ export default class TokenService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Générer un nouveau access token
|
// Générer un nouveau access token
|
||||||
const newAccessToken = await new jose.SignJWT({ origin, type: 'access' })
|
const newAccessToken = await new jose.SignJWT({ origin, type: 'access' }).setProtectedHeader({ alg: 'HS256' }).setIssuedAt().setExpirationTime(this.ACCESS_TOKEN_EXPIRATION).sign(secret);
|
||||||
.setProtectedHeader({ alg: 'HS256' })
|
|
||||||
.setIssuedAt()
|
|
||||||
.setExpirationTime(this.ACCESS_TOKEN_EXPIRATION)
|
|
||||||
.sign(secret);
|
|
||||||
|
|
||||||
return newAccessToken;
|
return newAccessToken;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
64
src/types/sdk_client.d.ts
vendored
64
src/types/sdk_client.d.ts
vendored
@ -3,11 +3,11 @@
|
|||||||
|
|
||||||
declare module 'pkg/sdk_client' {
|
declare module 'pkg/sdk_client' {
|
||||||
// Types de base
|
// Types de base
|
||||||
export type DiffStatus = "None" | "Rejected" | "Validated";
|
export type DiffStatus = 'None' | 'Rejected' | 'Validated';
|
||||||
export type AnkFlag = "NewTx" | "Faucet" | "Cipher" | "Commit" | "Handshake" | "Sync" | "Unknown";
|
export type AnkFlag = 'NewTx' | 'Faucet' | 'Cipher' | 'Commit' | 'Handshake' | 'Sync' | 'Unknown';
|
||||||
export type PrdType = "None" | "Connect" | "Message" | "Update" | "List" | "Response" | "Confirm" | "TxProposal" | "Request";
|
export type PrdType = 'None' | 'Connect' | 'Message' | 'Update' | 'List' | 'Response' | 'Confirm' | 'TxProposal' | 'Request';
|
||||||
export type SyncType = "StateSync" | "ProcessSync" | "MemberSync" | "TxSync" | "BlockSync" | "PeerSync" | "RelaySync" | "HealthSync" | "MetricsSync" | "ConfigSync" | "CapabilitySync";
|
export type SyncType = 'StateSync' | 'ProcessSync' | 'MemberSync' | 'TxSync' | 'BlockSync' | 'PeerSync' | 'RelaySync' | 'HealthSync' | 'MetricsSync' | 'ConfigSync' | 'CapabilitySync';
|
||||||
export type HealthStatus = "Healthy" | "Warning" | "Critical" | "Offline";
|
export type HealthStatus = 'Healthy' | 'Warning' | 'Critical' | 'Offline';
|
||||||
export type OutPoint = string;
|
export type OutPoint = string;
|
||||||
export type SilentPaymentAddress = string;
|
export type SilentPaymentAddress = string;
|
||||||
export type AnkSharedSecretHash = string;
|
export type AnkSharedSecretHash = string;
|
||||||
@ -186,52 +186,14 @@ declare module 'pkg/sdk_client' {
|
|||||||
export function get_available_amount(): bigint;
|
export function get_available_amount(): bigint;
|
||||||
export function create_transaction(addresses: string[], fee_rate: number): ApiReturn;
|
export function create_transaction(addresses: string[], fee_rate: number): ApiReturn;
|
||||||
export function sign_transaction(partial_tx: TsUnsignedTransaction): ApiReturn;
|
export function sign_transaction(partial_tx: TsUnsignedTransaction): ApiReturn;
|
||||||
export function create_new_process(
|
export function create_new_process(private_data: Pcd, roles: Roles, public_data: Pcd, relay_address: string, fee_rate: number, members_list: OutPointMemberMap): ApiReturn;
|
||||||
private_data: Pcd,
|
export function update_process(process: Process, new_attributes: Pcd, roles: Roles, new_public_data: Pcd, members_list: OutPointMemberMap): ApiReturn;
|
||||||
roles: Roles,
|
export function request_data(process_id: string, state_ids_str: string[], roles: any, members_list: OutPointMemberMap): ApiReturn;
|
||||||
public_data: Pcd,
|
export function create_update_message(process: Process, state_id: string, members_list: OutPointMemberMap): ApiReturn;
|
||||||
relay_address: string,
|
export function validate_state(process: Process, state_id: string, members_list: OutPointMemberMap): ApiReturn;
|
||||||
fee_rate: number,
|
export function refuse_state(process: Process, state_id: string, members_list: OutPointMemberMap): ApiReturn;
|
||||||
members_list: OutPointMemberMap
|
export function evaluate_state(process: Process, state_id: string, members_list: OutPointMemberMap): ApiReturn;
|
||||||
): ApiReturn;
|
export function create_response_prd(process: Process, state_id: string, members_list: OutPointMemberMap): ApiReturn;
|
||||||
export function update_process(
|
|
||||||
process: Process,
|
|
||||||
new_attributes: Pcd,
|
|
||||||
roles: Roles,
|
|
||||||
new_public_data: Pcd,
|
|
||||||
members_list: OutPointMemberMap
|
|
||||||
): ApiReturn;
|
|
||||||
export function request_data(
|
|
||||||
process_id: string,
|
|
||||||
state_ids_str: string[],
|
|
||||||
roles: any,
|
|
||||||
members_list: OutPointMemberMap
|
|
||||||
): ApiReturn;
|
|
||||||
export function create_update_message(
|
|
||||||
process: Process,
|
|
||||||
state_id: string,
|
|
||||||
members_list: OutPointMemberMap
|
|
||||||
): ApiReturn;
|
|
||||||
export function validate_state(
|
|
||||||
process: Process,
|
|
||||||
state_id: string,
|
|
||||||
members_list: OutPointMemberMap
|
|
||||||
): ApiReturn;
|
|
||||||
export function refuse_state(
|
|
||||||
process: Process,
|
|
||||||
state_id: string,
|
|
||||||
members_list: OutPointMemberMap
|
|
||||||
): ApiReturn;
|
|
||||||
export function evaluate_state(
|
|
||||||
process: Process,
|
|
||||||
state_id: string,
|
|
||||||
members_list: OutPointMemberMap
|
|
||||||
): ApiReturn;
|
|
||||||
export function create_response_prd(
|
|
||||||
process: Process,
|
|
||||||
state_id: string,
|
|
||||||
members_list: OutPointMemberMap
|
|
||||||
): ApiReturn;
|
|
||||||
export function create_faucet_msg(): string;
|
export function create_faucet_msg(): string;
|
||||||
export function get_storages(process_outpoint: string): string[];
|
export function get_storages(process_outpoint: string): string[];
|
||||||
export function is_child_role(parent_roles: string, child_roles: string): void;
|
export function is_child_role(parent_roles: string, child_roles: string): void;
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
export function splitPrivateData(data: Record<string, any>, privateFields: string[]): { privateData: Record<string, any>, publicData: Record<string, any> } {
|
export function splitPrivateData(data: Record<string, any>, privateFields: string[]): { privateData: Record<string, any>; publicData: Record<string, any> } {
|
||||||
const privateData: Record<string, any> = {};
|
const privateData: Record<string, any> = {};
|
||||||
const publicData: Record<string, any> = {};
|
const publicData: Record<string, any> = {};
|
||||||
|
|
||||||
|
@ -100,7 +100,7 @@ export async function displayEmojis(text: string) {
|
|||||||
|
|
||||||
// Verify Other address
|
// Verify Other address
|
||||||
export function initAddressInput() {
|
export function initAddressInput() {
|
||||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement
|
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
|
||||||
const addressInput = container.querySelector('#addressInput') as HTMLInputElement;
|
const addressInput = container.querySelector('#addressInput') as HTMLInputElement;
|
||||||
const emojiDisplay = container.querySelector('#emoji-display-2');
|
const emojiDisplay = container.querySelector('#emoji-display-2');
|
||||||
const okButton = container.querySelector('#okButton') as HTMLButtonElement;
|
const okButton = container.querySelector('#okButton') as HTMLButtonElement;
|
||||||
@ -170,10 +170,7 @@ export async function prepareAndSendPairingTx(): Promise<void> {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const relayAddress = service.getAllRelays();
|
const relayAddress = service.getAllRelays();
|
||||||
const createPairingProcessReturn = await service.createPairingProcess(
|
const createPairingProcessReturn = await service.createPairingProcess('', []);
|
||||||
"",
|
|
||||||
[],
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!createPairingProcessReturn.updated_process) {
|
if (!createPairingProcessReturn.updated_process) {
|
||||||
throw new Error('createPairingProcess returned an empty new process');
|
throw new Error('createPairingProcess returned an empty new process');
|
||||||
@ -183,7 +180,6 @@ export async function prepareAndSendPairingTx(): Promise<void> {
|
|||||||
service.setStateId(createPairingProcessReturn.updated_process.current_process.states[0].state_id);
|
service.setStateId(createPairingProcessReturn.updated_process.current_process.states[0].state_id);
|
||||||
|
|
||||||
await service.handleApiReturn(createPairingProcessReturn);
|
await service.handleApiReturn(createPairingProcessReturn);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
}
|
}
|
||||||
@ -191,7 +187,7 @@ export async function prepareAndSendPairingTx(): Promise<void> {
|
|||||||
|
|
||||||
export async function generateQRCode(spAddress: string) {
|
export async function generateQRCode(spAddress: string) {
|
||||||
try {
|
try {
|
||||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement
|
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
|
||||||
const currentUrl = 'https://' + window.location.host;
|
const currentUrl = 'https://' + window.location.host;
|
||||||
const url = await QRCode.toDataURL(currentUrl + '?sp_address=' + spAddress);
|
const url = await QRCode.toDataURL(currentUrl + '?sp_address=' + spAddress);
|
||||||
const qrCode = container?.querySelector('.qr-code img');
|
const qrCode = container?.querySelector('.qr-code img');
|
||||||
@ -204,7 +200,7 @@ export async function generateQRCode(spAddress: string) {
|
|||||||
export async function generateCreateBtn() {
|
export async function generateCreateBtn() {
|
||||||
try {
|
try {
|
||||||
//Generate CreateBtn
|
//Generate CreateBtn
|
||||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement
|
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
|
||||||
const createBtn = container?.querySelector('.create-btn');
|
const createBtn = container?.querySelector('.create-btn');
|
||||||
if (createBtn) {
|
if (createBtn) {
|
||||||
createBtn.textContent = 'CREATE';
|
createBtn.textContent = 'CREATE';
|
||||||
@ -212,5 +208,4 @@ export async function generateCreateBtn() {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
Loading…
x
Reference in New Issue
Block a user