style: formatage Prettier sur src/
Some checks failed
CI/CD Pipeline / test (push) Failing after 18s
CI/CD Pipeline / security (push) Has been skipped
CI/CD Pipeline / integration-test (push) Has been skipped

This commit is contained in:
Your Name 2025-08-26 12:49:27 +02:00
parent 2567e2f0da
commit 93d61c1e9c
27 changed files with 1075 additions and 1147 deletions

View File

@ -158,12 +158,12 @@ async function createBackUp() {
const service = await Services.getInstance();
const backUp = await service.createBackUp();
if (!backUp) {
console.error("No device to backup");
console.error('No device to backup');
return;
}
try {
const backUpJson = JSON.stringify(backUp, null, 2)
const backUpJson = JSON.stringify(backUp, null, 2);
const blob = new Blob([backUpJson], { type: 'application/json' });
const url = URL.createObjectURL(blob);
@ -201,7 +201,7 @@ async function disconnect() {
});
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');
await navigate('home');
@ -209,7 +209,6 @@ async function disconnect() {
setTimeout(() => {
window.location.href = window.location.origin;
}, 100);
} catch (error) {
console.error('Error during disconnect:', error);
// force reload

View File

@ -1,8 +1,6 @@
<div id="waiting-modal" class="modal">
<div class="modal-content">
<div class="modal-title">Login</div>
<div class="message">
Waiting for Device 2...
</div>
<div class="message">Waiting for Device 2...</div>
</div>
</div>

View File

@ -1,9 +1,7 @@
<div id="validation-modal" class="validation-modal">
<div class="modal-content">
<div class="modal-title">Validate Process {{processId}}</div>
<div class="validation-box">
</div>
<div class="validation-box"></div>
<div class="modal-action">
<button onclick="validate()">Validate</button>
</div>

View File

@ -7,9 +7,9 @@ async function validate() {
}
export async function initValidationModal(processDiffs: any) {
console.log("🚀 ~ initValidationModal ~ processDiffs:", processDiffs)
console.log('🚀 ~ initValidationModal ~ processDiffs:', processDiffs);
for (const diff of processDiffs.diffs) {
let diffs = ''
let diffs = '';
for (const value of diff) {
diffs += `
<div class="radio-buttons">
@ -30,7 +30,7 @@ for(const diff of processDiffs.diffs) {
<pre>+${value.new_value}</pre>
</div>
</div>
`
`;
}
const state = `
@ -40,9 +40,9 @@ for(const diff of processDiffs.diffs) {
${diffs}
</div>
</div>
`
const box = document.querySelector('.validation-box')
if(box) box.innerHTML += state
`;
const box = document.querySelector('.validation-box');
if (box) box.innerHTML += state;
}
document.querySelectorAll('.expansion-panel-header').forEach((header) => {
header.addEventListener('click', function (event) {

View File

@ -1,42 +1,25 @@
<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;
">
<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>
<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">
<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:
<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 style="display: block; margin-bottom: 0.5rem;">
<label style="display: block; margin-bottom: 0.5rem">
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 style="display: block; margin-bottom: 1rem;">
<label style="display: block; margin-bottom: 1rem">
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>
<div style="display: flex; justify-content: flex-end; gap: 1rem;">
<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>
<div style="display: flex; justify-content: flex-end; gap: 1rem">
<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>
</div>
</div>
</div>

View File

@ -52,7 +52,10 @@ export function showValidationRuleModal(onSubmit: (rule: ValidationRule) => void
const rule: ValidationRule = {
quorum: parseInt(quorumInput.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';

View File

@ -1,7 +1,7 @@
import { Device, Process, SecretsStore } from "pkg/sdk_client";
import { Device, Process, SecretsStore } from 'pkg/sdk_client';
export interface BackUp {
device: Device,
secrets: SecretsStore,
processes: Record<string, Process>,
device: Device;
secrets: SecretsStore;
processes: Record<string, Process>;
}

View File

@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<title>Account</title>

View File

@ -197,7 +197,6 @@ class AccountElement extends HTMLElement {
</div>
`;
window.showPairing = () => this.showPairing();
window.showWallet = () => this.showWallet();
window.showProcess = () => this.showProcess();
@ -281,7 +280,6 @@ class AccountElement extends HTMLElement {
}, 3000);
}
// Fonctions de gestion des comptes et de l'interface utilisateur
private confirmDeleteAccount(): void {
const modal = document.createElement('div');
@ -346,7 +344,6 @@ private loadSavedBanner(): void {
}
}
private closeNotificationPopup(event: Event): void {
const target = event.target as HTMLElement;
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 {
const process = mockProcessRows.find(p => p.process === processName);
const process = mockProcessRows.find((p) => p.process === processName);
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;
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
private calculateNotifications(messages: NotificationMessage[]): { unread: number; total: number } {
const total = messages.length;
const unread = messages.filter(msg => !msg.read).length;
const unread = messages.filter((msg) => !msg.read).length;
return { unread, total };
}
@ -412,8 +409,8 @@ private exportRecovery(): void {
// Ajouter des styles personnalisés
customClass: {
container: 'recovery-popup-container',
popup: 'recovery-popup'
}
popup: 'recovery-popup',
},
}).then((result) => {
if (result.isConfirmed) {
const recoveryWords = this.generateRecoveryWords();
@ -423,12 +420,16 @@ private exportRecovery(): void {
title: 'Your Recovery Words',
html: `
<div class="recovery-words-container">
${recoveryWords.map((word, index) => `
${recoveryWords
.map(
(word, index) => `
<div class="recovery-word">
<span class="word-number">${index + 1}.</span>
<span class="word">${word}</span>
</div>
`).join('')}
`,
)
.join('')}
</div>
<div class="recovery-warning">
Please write these words down carefully. They will be needed to recover your account.
@ -441,8 +442,8 @@ private exportRecovery(): void {
allowEscapeKey: false,
customClass: {
container: 'recovery-popup-container',
popup: 'recovery-popup'
}
popup: 'recovery-popup',
},
}).then((result) => {
if (result.isConfirmed) {
// Stocker l'état du bouton dans le localStorage
@ -461,10 +462,7 @@ private exportRecovery(): void {
}
private generateRecoveryWords(): string[] {
const wordsList = [
'apple', 'banana', 'orange', 'grape', 'kiwi', 'mango', 'peach', 'plum',
'lemon', 'lime', 'cherry', 'melon', 'pear', 'fig', 'date', 'berry'
];
const wordsList = ['apple', 'banana', 'orange', 'grape', 'kiwi', 'mango', 'peach', 'plum', 'lemon', 'lime', 'cherry', 'melon', 'pear', 'fig', 'date', 'berry'];
const recoveryWords: string[] = [];
while (recoveryWords.length < 4) {
const randomWord = wordsList[Math.floor(Math.random() * wordsList.length)];
@ -597,7 +595,7 @@ private async addRowPairing(): Promise<void> {
const newRow: Row = {
column1: spAddress,
column2: deviceName,
column3: spEmojis || ''
column3: spEmojis || '',
};
const storageKey = STORAGE_KEYS[currentMode];
@ -622,7 +620,9 @@ private updateTableContent(rows: Row[]): void {
const tbody = this.shadowRoot?.querySelector('#pairing-table tbody');
if (!tbody) return;
tbody.innerHTML = rows.map(row => `
tbody.innerHTML = rows
.map(
(row) => `
<tr>
<td class="device-name" onclick="window.editDeviceName(this)">${row.column2}</td>
<td>${row.column3}</td>
@ -641,19 +641,19 @@ private updateTableContent(rows: Row[]): void {
</button>
</td>
</tr>
`).join('');
`,
)
.join('');
}
private confirmRowPairing(): void {
if (!currentRow) return;
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
if (values.some(value => value === '')) {
if (values.some((value) => value === '')) {
this.showAlert('Please fill in all fields');
return;
}
@ -667,7 +667,7 @@ private confirmRowPairing(): void {
const newRow: Row = {
column1: values[0],
column2: values[1],
column3: values[2]
column3: values[2],
};
const storageKey = STORAGE_KEYS[currentMode];
@ -858,13 +858,14 @@ private async showProcess(): Promise<void> {
const service = await Services.getInstance();
const myProcesses = await service.getMyProcesses();
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 lastState = process ? service.getLastCommitedState(process) : null;
if (!lastState) {
return {
name: '',
publicData: {}
publicData: {},
};
}
const description = await service.decryptAttribute(processId, lastState, 'description');
@ -873,17 +874,16 @@ private async showProcess(): Promise<void> {
if (!publicData) {
return {
name: '',
publicData: {}
publicData: {},
};
}
return {
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);
} else {
@ -893,21 +893,24 @@ private async showProcess(): Promise<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;
const modal = document.createElement('div');
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'}"
onclick="window.markAsRead('${processName}', ${msg.id}, this)">
<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"/>
</svg>` :
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="16" height="16" fill="black">
</svg>`
: `<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"/>
</svg>`
}
@ -917,7 +920,9 @@ private showProcessNotifications(processName: string): void {
<small>${msg.date}</small>
</div>
</div>
`).join('');
`,
)
.join('');
if (process.notification.messages.length === 0) {
notificationsList = '<p>No notifications</p>';
@ -949,13 +954,11 @@ private showProcessNotifications(processName: string): void {
});
}
private handleLogout(): void {
localStorage.clear();
window.location.href = '../login/login.html';
}
// Fonctions de gestion des contrats
private showContractPopup(contractId: string, event?: Event) {
if (event) {
@ -980,7 +983,7 @@ private showContractPopup(contractId: string, event?: Event) {
<p><strong>Parties:</strong> ${contract.parties.join(', ')}</p>
<p><strong>Terms:</strong></p>
<ul>
${contract.terms.map(term => `<li>${term}</li>`).join('')}
${contract.terms.map((term) => `<li>${term}</li>`).join('')}
</ul>
<p><strong>Content:</strong> ${contract.content}</p>
</div>
@ -1001,7 +1004,7 @@ private showContractPopup(contractId: string, event?: Event) {
// Fonction utilitaire pour cacher tous les contenus
private hideAllContent(): void {
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);
if (element) {
element.style.display = 'none';
@ -1063,15 +1066,14 @@ private async showPairing(): Promise<void> {
const pairingProcess = await service.getProcess(pairingProcessId);
console.log('Pairing Process:', pairingProcess);
const userName = pairingProcess?.states?.[0]?.public_data?.memberPublicName
|| localStorage.getItem('userName')
const userName = pairingProcess?.states?.[0]?.public_data?.memberPublicName || localStorage.getItem('userName');
console.log('Username found:', userName);
const newRow = {
column1: spAddress,
column2: userName,
column3: emojis
column3: emojis,
};
rows = [newRow, ...rows];
localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows));
@ -1080,7 +1082,7 @@ private async showPairing(): Promise<void> {
const newRow = {
column1: spAddress,
column2: 'This Device',
column3: emojis
column3: emojis,
};
rows = [newRow, ...rows];
localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows));
@ -1128,18 +1130,21 @@ private showWallet(): void {
this.updateWalletTableContent(rows);
}
private updateWalletTableContent(rows: WalletRow[]): void {
const tbody = this.shadowRoot?.querySelector('#wallet-table tbody');
if (!tbody) return;
tbody.innerHTML = rows.map(row => `
tbody.innerHTML = rows
.map(
(row) => `
<tr>
<td>${row.column1}</td>
<td>${row.column2}</td>
<td class="device-name" onclick="editDeviceName(this)">${row.column3}</td>
</tr>
`).join('');
`,
)
.join('');
}
private showData(): void {
@ -1188,7 +1193,7 @@ private addWalletRow(): void {
currentRow = table.insertRow();
const placeholders = ['Label', 'Wallet', 'Type'];
placeholders.forEach(placeholder => {
placeholders.forEach((placeholder) => {
const cell = currentRow!.insertCell();
const input = document.createElement('input');
input.type = 'text';
@ -1215,13 +1220,13 @@ private confirmWalletRow(): void {
if (!currentRow) return;
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) {
const newRow: WalletRow = {
column1: inputs[0].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) || '[]');
@ -1250,15 +1255,15 @@ private cancelWalletRow(): void {
buttonContainer.innerHTML = `
<button class="add-row-button button-style" onclick="window.addWalletRow()">Add a line</button>
`;
}
private updateDataTableContent(rows: DataRow[]): void {
const tbody = this.shadowRoot?.querySelector('#data-table tbody');
if (!tbody) return;
tbody.innerHTML = rows.map(row => `
tbody.innerHTML = rows
.map(
(row) => `
<tr>
<td>${row.column1}</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>
</td>
</tr>
`).join('');
`,
)
.join('');
}
// Fonctions de gestion de l'avatar et de la bannière
@ -1504,12 +1511,7 @@ private updateNavbarLastName(lastName: string): void {
}
}
private updateProfilePreview(data: {
avatar?: string,
banner?: string,
name?: string,
lastName?: string
}): void {
private updateProfilePreview(data: { avatar?: string; banner?: string; name?: string; lastName?: string }): void {
if (data.avatar) {
const previewAvatar = this.shadowRoot?.querySelector('.preview-avatar') as HTMLImageElement;
if (previewAvatar) previewAvatar.src = data.avatar;
@ -1538,7 +1540,7 @@ private initializeEventListeners() {
const editableFields = this.shadowRoot?.querySelectorAll<HTMLElement>('.editable');
if (editableFields) {
editableFields.forEach(field => {
editableFields.forEach((field) => {
field.addEventListener('click', () => {
if (!field.classList.contains('editing')) {
const currentValue = field.textContent || '';

View File

@ -47,8 +47,8 @@ export function getDocumentValidation(container: HTMLElement) {
file: null,
fileHash: null,
certificate: null,
commitmentHashes: []
}
commitmentHashes: [],
};
container.innerHTML = '';
container.style.cssText = `
@ -60,11 +60,7 @@ export function getDocumentValidation(container: HTMLElement) {
gap: 2rem;
`;
function createDropButton(
label: string,
onDrop: (file: File, updateVisuals: (file: File) => void) => void,
accept: string = '*/*'
): HTMLElement {
function createDropButton(label: string, onDrop: (file: File, updateVisuals: (file: File) => void) => void, accept: string = '*/*'): HTMLElement {
const wrapper = document.createElement('div');
wrapper.style.cssText = `
width: 200px;
@ -120,7 +116,7 @@ export function getDocumentValidation(container: HTMLElement) {
};
// === Handle drag-and-drop ===
wrapper.ondragover = e => {
wrapper.ondragover = (e) => {
e.preventDefault();
wrapper.style.background = '#e0e0e0';
};
@ -129,7 +125,7 @@ export function getDocumentValidation(container: HTMLElement) {
wrapper.style.background = '#f8f8f8';
};
wrapper.ondrop = e => {
wrapper.ondrop = (e) => {
e.preventDefault();
wrapper.style.background = '#f8f8f8';
@ -163,17 +159,10 @@ export function getDocumentValidation(container: HTMLElement) {
try {
const text = await file.text();
const json = JSON.parse(text);
if (
typeof json === 'object' &&
json !== null &&
typeof json.pcd_commitment === 'object' &&
typeof json.state_id === 'string'
) {
if (typeof json === 'object' && json !== null && typeof json.pcd_commitment === 'object' && typeof json.state_id === 'string') {
state.certificate = json as ProcessState;
state.commitmentHashes = Object.values(json.pcd_commitment).map((h: any) =>
(h as string).toLowerCase()
);
state.commitmentHashes = Object.values(json.pcd_commitment).map((h: any) => (h as string).toLowerCase());
updateVisuals(file);
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
const fileBlob = {
type: state.file.type,
data: new Uint8Array(await state.file.arrayBuffer())
data: new Uint8Array(await state.file.arrayBuffer()),
};
const service = await Services.getInstance();
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)) {
// 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);
console.log(`Found hash ${fileHex}`);
found = state.commitmentHashes.includes(fileHex);

View File

@ -33,14 +33,14 @@ export function createKeyValueSection(title: string, id: string, isRoleSection =
validationRules: ValidationRule[];
}[] = [];
type fileBlob = {
type: string,
data: Uint8Array
type: string;
data: Uint8Array;
};
const nonRoleRowStates: {
keyInput: HTMLInputElement,
valueInput: HTMLInputElement,
fileInput: HTMLInputElement,
fileBlob: fileBlob | null
keyInput: HTMLInputElement;
valueInput: HTMLInputElement;
fileInput: HTMLInputElement;
fileBlob: fileBlob | null;
}[] = [];
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';
members.placeholder = 'members';
storages.placeholder = 'storages';
[roleName, members, storages].forEach(input => {
[roleName, members, storages].forEach((input) => {
input.type = 'text';
input.style.cssText = inputStyle;
});
@ -76,7 +76,7 @@ export function createKeyValueSection(title: string, id: string, isRoleSection =
const rules: ValidationRule[] = [];
ruleButton.onclick = () => {
showValidationRuleModal(rule => {
showValidationRuleModal((rule) => {
rules.push(rule);
ruleButton.textContent = `Rules (${rules.length})`;
});
@ -122,13 +122,13 @@ export function createKeyValueSection(title: string, id: string, isRoleSection =
keyInput,
valueInput,
fileInput,
fileBlob: null as fileBlob | null
fileBlob: null as fileBlob | null,
};
nonRoleRowStates.push(rowState);
keyInput.placeholder = 'Key';
valueInput.placeholder = 'Value';
[keyInput, valueInput].forEach(input => {
[keyInput, valueInput].forEach((input) => {
input.type = 'text';
input.style.cssText = inputStyle;
});
@ -148,7 +148,7 @@ export function createKeyValueSection(title: string, id: string, isRoleSection =
const updateDeleteButtons = () => {
const rows = Array.from(rowContainer.children);
rows.forEach(row => {
rows.forEach((row) => {
const btn = row.querySelector('button:last-child') as HTMLButtonElement;
if (rows.length === 1) {
btn.disabled = true;
@ -172,9 +172,15 @@ export function createKeyValueSection(title: string, id: string, isRoleSection =
const key = row.roleNameInput.value.trim();
if (!key) continue;
data[key] = {
members: row.membersInput.value.split(',').map(x => x.trim()).filter(Boolean),
storages: row.storagesInput.value.split(',').map(x => x.trim()).filter(Boolean),
validation_rules: row.validationRules
members: row.membersInput.value
.split(',')
.map((x) => x.trim())
.filter(Boolean),
storages: row.storagesInput.value
.split(',')
.map((x) => x.trim())
.filter(Boolean),
validation_rules: row.validationRules,
};
}
return data;
@ -191,6 +197,6 @@ export function createKeyValueSection(title: string, id: string, isRoleSection =
}
return data;
}
}
},
};
}

View File

@ -63,8 +63,8 @@ export async function getProcessCreation(container: HTMLElement) {
if (!encryptedData) continue;
const filename = `${label}-${hash.slice(0, 8)}.bin`;
const blob = new Blob([encryptedData], { type: "application/octet-stream" });
const link = document.createElement("a");
const blob = new Blob([encryptedData], { type: 'application/octet-stream' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();

View File

@ -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.style.display = 'block';
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;';
container.appendChild(title);
processes.forEach(proc => {
processes.forEach((proc) => {
const card = document.createElement('div');
card.style.cssText = 'margin-bottom: 1rem; padding: 1rem; border: 1px solid #ddd; border-radius: 0.5rem; background: #fff;';

View File

@ -139,11 +139,11 @@ export async function registerAllListeners() {
{
type: MessageType.ERROR,
error: errorMsg,
messageId
messageId,
},
origin
origin,
);
}
};
// --- Handler functions ---
const handleRequestLink = async (event: MessageEvent) => {
@ -155,13 +155,14 @@ export async function registerAllListeners() {
type: MessageType.LINK_ACCEPTED,
accessToken: 'e2e-access',
refreshToken: 'e2e-refresh',
messageId: event.data.messageId
messageId: event.data.messageId,
};
window.parent.postMessage(acceptedMsg, event.origin);
return;
} else {
const modalService = await ModalService.getInstance();
const result = await modalService.showConfirmationModal({
const result = await modalService.showConfirmationModal(
{
title: 'Confirmation de liaison',
content: `
<div class="modal-confirmation">
@ -172,8 +173,10 @@ export async function registerAllListeners() {
</div>
`,
confirmText: 'Ajouter un service',
cancelText: 'Annuler'
}, true);
cancelText: 'Annuler',
},
true,
);
if (!result) {
const errorMsg = 'Failed to pair device: User refused to link';
errorResponse(errorMsg, event.origin, event.data.messageId);
@ -186,17 +189,14 @@ export async function registerAllListeners() {
type: MessageType.LINK_ACCEPTED,
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
messageId: event.data.messageId
messageId: event.data.messageId,
};
window.parent.postMessage(
acceptedMsg,
event.origin
);
window.parent.postMessage(acceptedMsg, event.origin);
} catch (error) {
const errorMsg = `Failed to generate tokens: ${error}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
const handleCreatePairing = async (event: MessageEvent) => {
if (event.data.type !== MessageType.CREATE_PAIRING) {
@ -230,14 +230,14 @@ export async function registerAllListeners() {
const successMsg = {
type: MessageType.PAIRING_CREATED,
pairingId,
messageId: event.data.messageId
messageId: event.data.messageId,
};
window.parent.postMessage(successMsg, event.origin);
} catch (e) {
const errorMsg = `Failed to create pairing process: ${e}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
const handleGetMyProcesses = async (event: MessageEvent) => {
if (event.data.type !== MessageType.GET_MY_PROCESSES) {
@ -263,15 +263,15 @@ export async function registerAllListeners() {
{
type: MessageType.GET_MY_PROCESSES,
myProcesses,
messageId: event.data.messageId
messageId: event.data.messageId,
},
event.origin
event.origin,
);
} catch (e) {
const errorMsg = `Failed to get processes: ${e}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
const handleGetProcesses = async (event: MessageEvent) => {
if (event.data.type !== MessageType.GET_PROCESSES) {
@ -300,15 +300,15 @@ export async function registerAllListeners() {
{
type: MessageType.PROCESSES_RETRIEVED,
processes,
messageId: event.data.messageId
messageId: event.data.messageId,
},
event.origin
event.origin,
);
} catch (e) {
const errorMsg = `Failed to get processes: ${e}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
/// We got a state for some process and return as many clear attributes as we can
const handleDecryptState = async (event: MessageEvent) => {
@ -333,7 +333,7 @@ export async function registerAllListeners() {
// Retrieve the state for the process
const process = await services.getProcess(processId);
if (!process) {
throw new Error('Can\'t find process');
throw new Error("Can't find process");
}
const state = services.getStateFromId(process, stateId);
@ -357,15 +357,15 @@ export async function registerAllListeners() {
{
type: MessageType.DATA_RETRIEVED,
data: res,
messageId: event.data.messageId
messageId: event.data.messageId,
},
event.origin
event.origin,
);
} catch (e) {
const errorMsg = `Failed to retrieve data: ${e}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
const handleValidateToken = async (event: MessageEvent) => {
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);
}
if (isE2E) {
window.parent.postMessage({
window.parent.postMessage(
{
type: MessageType.VALIDATE_TOKEN,
accessToken,
refreshToken,
isValid: true,
messageId: event.data.messageId
}, event.origin);
messageId: event.data.messageId,
},
event.origin,
);
return;
}
const isValid = await tokenService.validateToken(accessToken, event.origin);
window.parent.postMessage({
window.parent.postMessage(
{
type: MessageType.VALIDATE_TOKEN,
accessToken,
refreshToken,
isValid,
messageId: event.data.messageId
}, event.origin);
messageId: event.data.messageId,
},
event.origin,
);
};
const handleRenewToken = async (event: MessageEvent) => {
@ -411,12 +417,15 @@ export async function registerAllListeners() {
throw new Error('No refresh token provided');
}
if (isE2E) {
window.parent.postMessage({
window.parent.postMessage(
{
type: MessageType.RENEW_TOKEN,
accessToken: 'e2e-access-2',
refreshToken,
messageId: event.data.messageId
}, event.origin);
messageId: event.data.messageId,
},
event.origin,
);
return;
}
@ -426,17 +435,20 @@ export async function registerAllListeners() {
throw new Error('Failed to refresh token');
}
window.parent.postMessage({
window.parent.postMessage(
{
type: MessageType.RENEW_TOKEN,
accessToken: newAccessToken,
refreshToken,
messageId: event.data.messageId
}, event.origin);
messageId: event.data.messageId,
},
event.origin,
);
} catch (error) {
const errorMsg = `Failed to renew token: ${error}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
const handleGetPairingId = async (event: MessageEvent) => {
if (event.data.type !== MessageType.GET_PAIRING_ID) return;
@ -460,15 +472,15 @@ export async function registerAllListeners() {
{
type: MessageType.GET_PAIRING_ID,
userPairingId,
messageId: event.data.messageId
messageId: event.data.messageId,
},
event.origin
event.origin,
);
} catch (e) {
const errorMsg = `Failed to get pairing id: ${e}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
const handleCreateProcess = async (event: MessageEvent) => {
if (event.data.type !== MessageType.CREATE_PROCESS) return;
@ -483,11 +495,14 @@ export async function registerAllListeners() {
const { processData, privateFields, roles, accessToken } = event.data;
if (isE2E) {
window.parent.postMessage({
window.parent.postMessage(
{
type: MessageType.PROCESS_CREATED,
processCreated: { processId: 'e2e-process', process: {}, processData },
messageId: event.data.messageId
}, event.origin);
messageId: event.data.messageId,
},
event.origin,
);
return;
}
@ -507,16 +522,19 @@ export async function registerAllListeners() {
const res = { processId, process, processData };
window.parent.postMessage({
window.parent.postMessage(
{
type: MessageType.PROCESS_CREATED,
processCreated: res,
messageId: event.data.messageId
}, event.origin);
messageId: event.data.messageId,
},
event.origin,
);
} catch (e) {
const errorMsg = `Failed to create process: ${e}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
const handleNotifyUpdate = async (event: MessageEvent) => {
if (event.data.type !== MessageType.NOTIFY_UPDATE) return;
@ -544,15 +562,15 @@ export async function registerAllListeners() {
window.parent.postMessage(
{
type: MessageType.UPDATE_NOTIFIED,
messageId: event.data.messageId
messageId: event.data.messageId,
},
event.origin
event.origin,
);
} catch (e) {
const errorMsg = `Failed to notify update for process: ${e}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
const handleValidateState = async (event: MessageEvent) => {
if (event.data.type !== MessageType.VALIDATE_STATE) return;
@ -577,15 +595,15 @@ export async function registerAllListeners() {
{
type: MessageType.STATE_VALIDATED,
validatedProcess: res.updated_process,
messageId: event.data.messageId
messageId: event.data.messageId,
},
event.origin
event.origin,
);
} catch (e) {
const errorMsg = `Failed to validate process: ${e}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
const handleUpdateProcess = async (event: MessageEvent) => {
if (event.data.type !== MessageType.UPDATE_PROCESS) return;
@ -626,15 +644,15 @@ export async function registerAllListeners() {
}
}
// Wait a couple seconds
await new Promise(resolve => setTimeout(resolve, 2000));
await new Promise((resolve) => setTimeout(resolve, 2000));
lastState = services.getLastCommitedState(process);
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);
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
const privateData: Record<string, any> = {};
@ -686,15 +704,15 @@ export async function registerAllListeners() {
{
type: MessageType.PROCESS_UPDATED,
updatedProcess: res.updated_process,
messageId: event.data.messageId
messageId: event.data.messageId,
},
event.origin
event.origin,
);
} catch (e) {
const errorMsg = `Failed to update process: ${e}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
const handleDecodePublicData = async (event: MessageEvent) => {
if (event.data.type !== MessageType.DECODE_PUBLIC_DATA) return;
@ -718,15 +736,15 @@ export async function registerAllListeners() {
{
type: MessageType.PUBLIC_DATA_DECODED,
decodedData,
messageId: event.data.messageId
messageId: event.data.messageId,
},
event.origin
event.origin,
);
} catch (e) {
const errorMsg = `Failed to decode data: ${e}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
const handleHashValue = async (event: MessageEvent) => {
if (event.data.type !== MessageType.HASH_VALUE) return;
@ -746,15 +764,15 @@ export async function registerAllListeners() {
{
type: MessageType.VALUE_HASHED,
hash,
messageId: event.data.messageId
messageId: event.data.messageId,
},
event.origin
event.origin,
);
} catch (e) {
const errorMsg = `Failed to hash value: ${e}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
const handleGetMerkleProof = async (event: MessageEvent) => {
if (event.data.type !== MessageType.GET_MERKLE_PROOF) return;
@ -772,15 +790,15 @@ export async function registerAllListeners() {
{
type: MessageType.MERKLE_PROOF_RETRIEVED,
proof,
messageId: event.data.messageId
messageId: event.data.messageId,
},
event.origin
event.origin,
);
} catch (e) {
const errorMsg = `Failed to get merkle proof: ${e}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
const handleValidateMerkleProof = async (event: MessageEvent) => {
if (event.data.type !== MessageType.VALIDATE_MERKLE_PROOF) return;
@ -807,15 +825,15 @@ export async function registerAllListeners() {
{
type: MessageType.MERKLE_PROOF_VALIDATED,
isValid: res,
messageId: event.data.messageId
messageId: event.data.messageId,
},
event.origin
event.origin,
);
} catch (e) {
const errorMsg = `Failed to get merkle proof: ${e}`;
errorResponse(errorMsg, event.origin, event.data.messageId);
}
}
};
window.removeEventListener('message', handleMessage);
window.addEventListener('message', handleMessage);
@ -915,8 +933,8 @@ async function injectHeader() {
(window as any).navigate = navigate;
document.addEventListener('navigate', ((e: Event) => {
const event = e as CustomEvent<{page: string, processId?: string}>;
document.addEventListener('navigate', (e: Event) => {
const event = e as CustomEvent<{ page: string; processId?: string }>;
if (event.detail.page === 'chat') {
const container = document.querySelector('.container');
if (container) container.innerHTML = '';
@ -928,4 +946,4 @@ document.addEventListener('navigate', ((e: Event) => {
chatElement.setAttribute('process-id', event.detail.processId || '');
}
}
}));
});

View File

@ -139,7 +139,7 @@ async function getAllProcesses() {
reject(request.error);
};
});
};
}
async function getProcesses(processIds) {
if (!processIds || processIds.length === 0) {
@ -166,7 +166,7 @@ async function getProcesses(processIds) {
});
const results = await Promise.all(requests);
return results.filter(result => result !== undefined);
return results.filter((result) => result !== undefined);
}
async function getAllDiffsNeedValidation() {
@ -204,11 +204,11 @@ async function getAllDiffsNeedValidation() {
}
const results = Object.values(processMap).map((entry) => {
const diffs = []
const diffs = [];
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) {
diffs.push(filteredDiff)
diffs.push(filteredDiff);
}
}
return {
@ -265,7 +265,7 @@ async function addDiff(processId, stateId, hash, roles, field) {
new_value: null,
notify_user: false,
need_validation: false,
validation_status: 'None'
validation_status: 'None',
};
const insertResult = await new Promise((resolve, reject) => {

View File

@ -128,7 +128,7 @@ export class Database {
} else {
// More than one existing worker: unregister them all and register a new one.
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.');
this.serviceWorkerRegistration = await navigator.serviceWorker.register(path, { type: 'module' });
console.log('Service Worker registered with scope:', this.serviceWorkerRegistration.scope);
@ -217,15 +217,17 @@ export class Database {
const valueBytes = await service.fetchValueFromStorage(hash);
if (valueBytes) {
// 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);
document.dispatchEvent(new CustomEvent('newDataReceived', {
document.dispatchEvent(
new CustomEvent('newDataReceived', {
detail: {
processId,
stateId,
hash,
}
}));
},
}),
);
} else {
// We first request the data from managers
console.log('Request data from managers of the process');
@ -256,7 +258,7 @@ export class Database {
const valueBytes = await service.fetchValueFromStorage(hash);
if (valueBytes) {
// 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);
} else {
// We first request the data from managers
@ -440,7 +442,7 @@ export class Database {
const getAllRequest = index.getAll(request);
getAllRequest.onsuccess = () => {
const allItems = getAllRequest.result;
const filtered = allItems.filter(item => item.state_id === request);
const filtered = allItems.filter((item) => item.state_id === request);
resolve(filtered);
};
getAllRequest.onerror = () => reject(getAllRequest.error);

View File

@ -90,7 +90,7 @@ export default class ModalService {
const container = document.querySelector('#containerId');
if (container) {
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;
// Dynamically load the header JS
@ -103,7 +103,7 @@ export default class ModalService {
css.id = 'validation-modal-css';
css.innerText = validationModalStyle;
document.head.appendChild(css);
initValidationModal(processDiff)
initValidationModal(processDiff);
}
}
@ -129,7 +129,7 @@ export default class ModalService {
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
const service = await Services.getInstance();
const localAddress = service.getDeviceAddress();
@ -158,11 +158,11 @@ export default class ModalService {
if (members[0].sp_addresses.length === 1) {
await this.injectCreationModal(members);
this.modal = document.getElementById('creation-modal');
console.log("LENGTH:", members[0].sp_addresses.length);
console.log('LENGTH:', members[0].sp_addresses.length);
} else {
await this.injectModal(members);
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';

View File

@ -12,8 +12,8 @@ export const U32_MAX = 4294967295;
const BASEURL = `http://localhost`;
const BOOTSTRAPURL = [`${BASEURL}:8090`];
const STORAGEURL = `${BASEURL}:8081`
const BLINDBITURL = `${BASEURL}:8000`
const STORAGEURL = `${BASEURL}:8081`;
const BLINDBITURL = `${BASEURL}:8000`;
const DEFAULTAMOUNT = 1000n;
const EMPTY32BYTES = String('').padStart(64, '0');
@ -153,7 +153,7 @@ export default class Services {
* Print all key/value pairs for debugging.
*/
public printAllRelays(): void {
console.log("Current relay addresses:");
console.log('Current relay addresses:');
for (const [wsurl, spAddress] of Object.entries(this.relayAddresses)) {
console.log(`${wsurl} -> ${spAddress}`);
}
@ -307,27 +307,18 @@ export default class Services {
min_sig_member: 1.0,
},
],
storages: [STORAGEURL]
storages: [STORAGEURL],
},
};
try {
return this.createProcess(
privateData,
publicData,
roles
);
return this.createProcess(privateData, publicData, roles);
} catch (e) {
throw new Error(`Creating process failed:, ${e}`);
}
}
private isFileBlob(value: any): value is { type: string, data: Uint8Array } {
return (
typeof value === 'object' &&
value !== null &&
typeof value.type === 'string' &&
value.data instanceof Uint8Array
);
private isFileBlob(value: any): value is { type: string; data: Uint8Array } {
return typeof value === 'object' && value !== null && typeof value.type === 'string' && value.data instanceof Uint8Array;
}
private splitData(obj: Record<string, any>) {
@ -345,11 +336,7 @@ export default class Services {
return { jsonCompatibleData, binaryData };
}
public async createProcess(
privateData: Record<string, any>,
publicData: Record<string, any>,
roles: Record<string, RoleDefinition>,
): Promise<ApiReturn> {
public async createProcess(privateData: Record<string, any>, publicData: Record<string, any>, roles: Record<string, RoleDefinition>): Promise<ApiReturn> {
let relayAddress = this.getAllRelays()[0]?.spAddress;
if (!relayAddress || relayAddress === '') {
@ -372,11 +359,11 @@ export default class Services {
const publicSplitData = this.splitData(publicData);
const encodedPrivateData = {
...this.sdkClient.encode_json(privateSplitData.jsonCompatibleData),
...this.sdkClient.encode_binary(privateSplitData.binaryData)
...this.sdkClient.encode_binary(privateSplitData.binaryData),
};
const encodedPublicData = {
...this.sdkClient.encode_json(publicSplitData.jsonCompatibleData),
...this.sdkClient.encode_binary(publicSplitData.binaryData)
...this.sdkClient.encode_binary(publicSplitData.binaryData),
};
console.log('encoded data:', encodedPrivateData);
@ -395,16 +382,9 @@ export default class Services {
console.log('members:', members);
await this.checkConnections([...members]);
const result = this.sdkClient.create_new_process (
encodedPrivateData,
roles,
encodedPublicData,
relayAddress,
feeRate,
this.getAllMembers()
);
const result = this.sdkClient.create_new_process(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> {
@ -418,7 +398,7 @@ export default class Services {
let members: Set<Member> = new Set();
for (const role of Object.values(roles!)) {
for (const member of role.members) {
members.add(member)
members.add(member);
}
}
if (members.size === 0) {
@ -439,11 +419,11 @@ export default class Services {
const publicSplitData = this.splitData(publicData);
const encodedPrivateData = {
...this.sdkClient.encode_json(privateSplitData.jsonCompatibleData),
...this.sdkClient.encode_binary(privateSplitData.binaryData)
...this.sdkClient.encode_binary(privateSplitData.binaryData),
};
const encodedPublicData = {
...this.sdkClient.encode_json(publicSplitData.jsonCompatibleData),
...this.sdkClient.encode_binary(publicSplitData.binaryData)
...this.sdkClient.encode_binary(publicSplitData.binaryData),
};
try {
return this.sdkClient.update_process(process, encodedPrivateData, roles, encodedPublicData, this.getAllMembers());
@ -544,7 +524,6 @@ export default class Services {
if (waitingModal) {
this.device2Ready = true;
}
} catch (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) {
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) {
@ -789,7 +768,7 @@ export default class Services {
try {
let encodedSpAddressList: number[] = [];
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) {
encodedSpAddressList = state.public_data['pairedAddresses'];
}
@ -858,7 +837,7 @@ export default class Services {
try {
const prevDevice = await this.getDeviceFromDatabase();
if (prevDevice) {
await db.deleteObject(walletStore, "1");
await db.deleteObject(walletStore, '1');
}
await db.addObject({
storeName: walletStore,
@ -1256,7 +1235,7 @@ export default class Services {
let retries = 0;
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
hash = state.pcd_commitment[attribute];
key = state.keys[attribute];
@ -1373,7 +1352,6 @@ export default class Services {
this.device2Ready = false;
}
// Handle the handshake message
public async handleHandshakeMsg(url: string, parsedMsg: any) {
try {
@ -1414,7 +1392,9 @@ export default class Services {
let new_states: string[] = [];
let roles: Record<string, RoleDefinition>[] = [];
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.rolesContainsUs(state.roles)) {
new_states.push(state.state_id);
@ -1462,7 +1442,7 @@ export default class Services {
await this.batchSaveProcessesToDb(toSave);
}
}, 500)
}, 500);
} catch (e) {
console.error('Failed to parse init message:', e);
}
@ -1515,9 +1495,7 @@ export default class Services {
* @returns Un tableau contenant tous les membres
*/
public getAllMembersSorted(): Record<string, Member> {
return Object.fromEntries(
Object.entries(this.membersList).sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
);
return Object.fromEntries(Object.entries(this.membersList).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)));
}
public getAllMembers(): Record<string, Member> {
@ -1533,10 +1511,14 @@ export default class Services {
}
public compareMembers(memberA: string[], memberB: string[]): boolean {
if (!memberA || !memberB) { return false }
if (memberA.length !== memberB.length) { return false }
if (!memberA || !memberB) {
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;
}
@ -1545,16 +1527,14 @@ export default class Services {
const content = JSON.parse(response);
const error = content.error;
const errorMsg = error['GenericError'];
const dontRetry = [
'State is identical to the previous state',
'Not enough valid proofs',
'Not enough members to validate',
];
if (dontRetry.includes(errorMsg)) { return; }
const dontRetry = ['State is identical to the previous state', 'Not enough valid proofs', 'Not enough members to validate'];
if (dontRetry.includes(errorMsg)) {
return;
}
// Wait and retry
setTimeout(async () => {
this.sendCommitMessage(JSON.stringify(content));
}, 1000)
}, 1000);
}
public getRoles(process: Process): Record<string, RoleDefinition> | null {
@ -1587,8 +1567,11 @@ export default class Services {
const lastCommitedState = this.getLastCommitedState(process);
if (lastCommitedState && lastCommitedState.public_data) {
const processName = lastCommitedState!.public_data['processName'];
if (processName) { return this.decodeValue(processName) }
else { return null }
if (processName) {
return this.decodeValue(processName);
} else {
return null;
}
} else {
return null;
}
@ -1630,7 +1613,7 @@ export default class Services {
this.myProcesses = newMyProcesses; // atomic update
return Array.from(this.myProcesses);
} catch (e) {
console.error("Failed to get processes:", e);
console.error('Failed to get processes:', e);
return null;
}
}
@ -1652,12 +1635,12 @@ export default class Services {
const ab = new ArrayBuffer(uint8Array.length);
const view = new Uint8Array(ab);
view.set(uint8Array);
return new Blob([ab], { type: "application/octet-stream" });
return new Blob([ab], { type: 'application/octet-stream' });
}
public hexToUInt8Array(hexString: string): Uint8Array {
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);
for (let i = 0; i < hexString.length; i += 2) {
@ -1671,7 +1654,7 @@ export default class Services {
const buffer = await blob.arrayBuffer();
const bytes = new Uint8Array(buffer);
return Array.from(bytes)
.map(byte => byte.toString(16).padStart(2, '0'))
.map((byte) => byte.toString(16).padStart(2, '0'))
.join('');
}
@ -1743,7 +1726,9 @@ export default class Services {
}
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'];
if (pairingRole) {
// 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> {
const publicData = {
'memberPublicName': newName
memberPublicName: newName,
};
return await this.updateProcess(process, {}, publicData, null);

View File

@ -13,7 +13,7 @@ export async function storeData(servers: string[], key: string, value: Blob, ttl
// Send the encrypted ArrayBuffer as the raw request body.
const response = await axios.post(url.toString(), value, {
headers: {
'Content-Type': 'application/octet-stream'
'Content-Type': 'application/octet-stream',
},
});
console.log('Data stored successfully:', key);
@ -37,7 +37,7 @@ export async function retrieveData(servers: string[], key: string): Promise<Arra
try {
// When fetching the data from the server:
const response = await axios.get(`${server}/retrieve/${key}`, {
responseType: 'arraybuffer'
responseType: 'arraybuffer',
});
if (response.status !== 200) {
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);
}
}
return null
return null;
}
interface TestResponse {

View File

@ -38,17 +38,9 @@ export default class TokenService {
async generateSessionToken(origin: string): Promise<TokenPair> {
const secret = new Uint8Array(this.encoder.encode(this.SECRET_KEY));
const accessToken = await new jose.SignJWT({ origin, type: 'access' })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime(this.ACCESS_TOKEN_EXPIRATION)
.sign(secret);
const accessToken = await new jose.SignJWT({ origin, type: 'access' }).setProtectedHeader({ alg: 'HS256' }).setIssuedAt().setExpirationTime(this.ACCESS_TOKEN_EXPIRATION).sign(secret);
const refreshToken = await new jose.SignJWT({ origin, type: 'refresh' })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime(this.REFRESH_TOKEN_EXPIRATION)
.sign(secret);
const refreshToken = await new jose.SignJWT({ origin, type: 'refresh' }).setProtectedHeader({ alg: 'HS256' }).setIssuedAt().setExpirationTime(this.REFRESH_TOKEN_EXPIRATION).sign(secret);
return { accessToken, refreshToken };
}
@ -86,11 +78,7 @@ export default class TokenService {
}
// Générer un nouveau access token
const newAccessToken = await new jose.SignJWT({ origin, type: 'access' })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime(this.ACCESS_TOKEN_EXPIRATION)
.sign(secret);
const newAccessToken = await new jose.SignJWT({ origin, type: 'access' }).setProtectedHeader({ alg: 'HS256' }).setIssuedAt().setExpirationTime(this.ACCESS_TOKEN_EXPIRATION).sign(secret);
return newAccessToken;
} catch (error) {

View File

@ -3,11 +3,11 @@
declare module 'pkg/sdk_client' {
// Types de base
export type DiffStatus = "None" | "Rejected" | "Validated";
export type AnkFlag = "NewTx" | "Faucet" | "Cipher" | "Commit" | "Handshake" | "Sync" | "Unknown";
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 HealthStatus = "Healthy" | "Warning" | "Critical" | "Offline";
export type DiffStatus = 'None' | 'Rejected' | 'Validated';
export type AnkFlag = 'NewTx' | 'Faucet' | 'Cipher' | 'Commit' | 'Handshake' | 'Sync' | 'Unknown';
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 HealthStatus = 'Healthy' | 'Warning' | 'Critical' | 'Offline';
export type OutPoint = string;
export type SilentPaymentAddress = string;
export type AnkSharedSecretHash = string;
@ -186,52 +186,14 @@ declare module 'pkg/sdk_client' {
export function get_available_amount(): bigint;
export function create_transaction(addresses: string[], fee_rate: number): ApiReturn;
export function sign_transaction(partial_tx: TsUnsignedTransaction): ApiReturn;
export function create_new_process(
private_data: Pcd,
roles: Roles,
public_data: Pcd,
relay_address: string,
fee_rate: number,
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_new_process(private_data: Pcd, roles: Roles, public_data: Pcd, relay_address: string, fee_rate: number, 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 get_storages(process_outpoint: string): string[];
export function is_child_role(parent_roles: string, child_roles: string): void;

View File

@ -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 publicData: Record<string, any> = {};

View File

@ -100,7 +100,7 @@ export async function displayEmojis(text: string) {
// Verify Other address
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 emojiDisplay = container.querySelector('#emoji-display-2');
const okButton = container.querySelector('#okButton') as HTMLButtonElement;
@ -170,10 +170,7 @@ export async function prepareAndSendPairingTx(): Promise<void> {
try {
const relayAddress = service.getAllRelays();
const createPairingProcessReturn = await service.createPairingProcess(
"",
[],
);
const createPairingProcessReturn = await service.createPairingProcess('', []);
if (!createPairingProcessReturn.updated_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);
await service.handleApiReturn(createPairingProcessReturn);
} catch (err) {
console.error(err);
}
@ -191,7 +187,7 @@ export async function prepareAndSendPairingTx(): Promise<void> {
export async function generateQRCode(spAddress: string) {
try {
const container = getCorrectDOM('login-4nk-component') as HTMLElement
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
const currentUrl = 'https://' + window.location.host;
const url = await QRCode.toDataURL(currentUrl + '?sp_address=' + spAddress);
const qrCode = container?.querySelector('.qr-code img');
@ -204,7 +200,7 @@ export async function generateQRCode(spAddress: string) {
export async function generateCreateBtn() {
try {
//Generate CreateBtn
const container = getCorrectDOM('login-4nk-component') as HTMLElement
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
const createBtn = container?.querySelector('.create-btn');
if (createBtn) {
createBtn.textContent = 'CREATE';
@ -212,5 +208,4 @@ export async function generateCreateBtn() {
} catch (err) {
console.error(err);
}
}