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 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
|
||||
|
@ -1,14 +1,14 @@
|
||||
<div id="creation-modal" class="modal">
|
||||
<div class="modal-content">
|
||||
<div class="modal-title">Login</div>
|
||||
<div class="message">
|
||||
Do you want to create a 4NK member?<br />
|
||||
Attempting to create a member with address <br />
|
||||
<strong>{{device1}}</strong> <br />
|
||||
</div>
|
||||
<div class="confirmation-box">
|
||||
<a class="btn confirmation-btn" onclick="confirm()">Confirm</a>
|
||||
<a class="btn refusal-btn" onclick="closeConfirmationModal()">Refuse</a>
|
||||
</div>
|
||||
<div class="modal-content">
|
||||
<div class="modal-title">Login</div>
|
||||
<div class="message">
|
||||
Do you want to create a 4NK member?<br />
|
||||
Attempting to create a member with address <br />
|
||||
<strong>{{device1}}</strong> <br />
|
||||
</div>
|
||||
<div class="confirmation-box">
|
||||
<a class="btn confirmation-btn" onclick="confirm()">Confirm</a>
|
||||
<a class="btn refusal-btn" onclick="closeConfirmationModal()">Refuse</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -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>
|
||||
<div class="modal-content">
|
||||
<div class="modal-title">Login</div>
|
||||
<div class="message">Waiting for Device 2...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -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>
|
||||
|
@ -7,11 +7,11 @@ async function validate() {
|
||||
}
|
||||
|
||||
export async function initValidationModal(processDiffs: any) {
|
||||
console.log("🚀 ~ initValidationModal ~ processDiffs:", processDiffs)
|
||||
for(const diff of processDiffs.diffs) {
|
||||
let diffs = ''
|
||||
for(const value of diff) {
|
||||
diffs+= `
|
||||
console.log('🚀 ~ initValidationModal ~ processDiffs:', processDiffs);
|
||||
for (const diff of processDiffs.diffs) {
|
||||
let diffs = '';
|
||||
for (const value of diff) {
|
||||
diffs += `
|
||||
<div class="radio-buttons">
|
||||
<label>
|
||||
<input type="radio" name="validation1" value="old" />
|
||||
@ -30,27 +30,27 @@ for(const diff of processDiffs.diffs) {
|
||||
<pre>+${value.new_value}</pre>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
const state = `
|
||||
const state = `
|
||||
<div class="expansion-panel">
|
||||
<div class="expansion-panel-header">State ${diff[0].new_state_merkle_root}</div>
|
||||
<div class="expansion-panel-body">
|
||||
${diffs}
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
const box = document.querySelector('.validation-box')
|
||||
if(box) box.innerHTML += state
|
||||
}
|
||||
document.querySelectorAll('.expansion-panel-header').forEach((header) => {
|
||||
header.addEventListener('click', function (event) {
|
||||
const target = event.target as HTMLElement;
|
||||
const body = target.nextElementSibling as HTMLElement;
|
||||
if (body?.style) body.style.display = body.style.display === 'block' ? 'none' : 'block';
|
||||
`;
|
||||
const box = document.querySelector('.validation-box');
|
||||
if (box) box.innerHTML += state;
|
||||
}
|
||||
document.querySelectorAll('.expansion-panel-header').forEach((header) => {
|
||||
header.addEventListener('click', function (event) {
|
||||
const target = event.target as HTMLElement;
|
||||
const body = target.nextElementSibling as HTMLElement;
|
||||
if (body?.style) body.style.display = body.style.display === 'block' ? 'none' : 'block';
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
(window as any).validate = validate;
|
||||
|
@ -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>
|
||||
|
@ -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';
|
||||
|
@ -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>;
|
||||
}
|
||||
|
@ -1,10 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<head>
|
||||
<title>Account</title>
|
||||
</head>
|
||||
<body>
|
||||
</head>
|
||||
<body>
|
||||
<account-component></account-component>
|
||||
<script type="module" src="./account.ts"></script>
|
||||
</body>
|
||||
</body>
|
||||
</html>
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -9,8 +9,8 @@ interface State {
|
||||
}
|
||||
|
||||
export interface Vin {
|
||||
txid: string; // The txid of the previous transaction (being spent)
|
||||
vout: number; // The output index in the previous tx
|
||||
txid: string; // The txid of the previous transaction (being spent)
|
||||
vout: number; // The output index in the previous tx
|
||||
prevout: {
|
||||
scriptpubkey: string;
|
||||
scriptpubkey_asm: string;
|
||||
@ -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);
|
||||
|
@ -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;
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
@ -61,10 +61,10 @@ export async function getProcessCreation(container: HTMLElement) {
|
||||
const hash = newState.pcd_commitment[label];
|
||||
const encryptedData = await service.getBlobFromDb(hash);
|
||||
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 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();
|
||||
|
@ -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;';
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
import Routing from '../../services/modal.service';
|
||||
import Services from '../../services/service';
|
||||
import { addSubscription } from '../../utils/subscription.utils';
|
||||
import { displayEmojis, generateQRCode, generateCreateBtn, addressToEmoji} from '../../utils/sp-address.utils';
|
||||
import { displayEmojis, generateQRCode, generateCreateBtn, addressToEmoji } from '../../utils/sp-address.utils';
|
||||
import { getCorrectDOM } from '../../utils/html.utils';
|
||||
import QrScannerComponent from '../../components/qrcode-scanner/qrcode-scanner-component';
|
||||
import { navigate, registerAllListeners } from '../../router';
|
||||
|
218
src/router.ts
218
src/router.ts
@ -111,9 +111,9 @@ export async function init(): Promise<void> {
|
||||
await services.restoreSecretsFromDB();
|
||||
|
||||
if (!isE2E) {
|
||||
// We connect to all relays now
|
||||
await services.connectAllRelays();
|
||||
await services.updateDeviceBlockHeight();
|
||||
// We connect to all relays now
|
||||
await services.connectAllRelays();
|
||||
await services.updateDeviceBlockHeight();
|
||||
}
|
||||
|
||||
// We register all the event listeners if we run in an iframe
|
||||
@ -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,15 +155,16 @@ 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({
|
||||
title: 'Confirmation de liaison',
|
||||
content: `
|
||||
const modalService = await ModalService.getInstance();
|
||||
const result = await modalService.showConfirmationModal(
|
||||
{
|
||||
title: 'Confirmation de liaison',
|
||||
content: `
|
||||
<div class="modal-confirmation">
|
||||
<h3>Liaison avec ${event.origin}</h3>
|
||||
<p>Vous êtes sur le point de lier l'identité numérique de la clé securisée propre à votre appareil avec ${event.origin}.</p>
|
||||
@ -171,12 +172,14 @@ export async function registerAllListeners() {
|
||||
<p>Voulez-vous continuer ?</p>
|
||||
</div>
|
||||
`,
|
||||
confirmText: 'Ajouter un service',
|
||||
cancelText: 'Annuler'
|
||||
}, true);
|
||||
if (!result) {
|
||||
const errorMsg = 'Failed to pair device: User refused to link';
|
||||
errorResponse(errorMsg, event.origin, event.data.messageId);
|
||||
confirmText: 'Ajouter un service',
|
||||
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({
|
||||
type: MessageType.VALIDATE_TOKEN,
|
||||
accessToken,
|
||||
refreshToken,
|
||||
isValid: true,
|
||||
messageId: event.data.messageId
|
||||
}, event.origin);
|
||||
window.parent.postMessage(
|
||||
{
|
||||
type: MessageType.VALIDATE_TOKEN,
|
||||
accessToken,
|
||||
refreshToken,
|
||||
isValid: true,
|
||||
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);
|
||||
accessToken,
|
||||
refreshToken,
|
||||
isValid,
|
||||
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({
|
||||
type: MessageType.RENEW_TOKEN,
|
||||
accessToken: 'e2e-access-2',
|
||||
refreshToken,
|
||||
messageId: event.data.messageId
|
||||
}, event.origin);
|
||||
window.parent.postMessage(
|
||||
{
|
||||
type: MessageType.RENEW_TOKEN,
|
||||
accessToken: 'e2e-access-2',
|
||||
refreshToken,
|
||||
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);
|
||||
refreshToken,
|
||||
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({
|
||||
type: MessageType.PROCESS_CREATED,
|
||||
processCreated: { processId: 'e2e-process', process: {}, processData },
|
||||
messageId: event.data.messageId
|
||||
}, event.origin);
|
||||
window.parent.postMessage(
|
||||
{
|
||||
type: MessageType.PROCESS_CREATED,
|
||||
processCreated: { processId: 'e2e-process', process: {}, processData },
|
||||
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;
|
||||
@ -614,7 +632,7 @@ export async function registerAllListeners() {
|
||||
const firstState = process.states[0];
|
||||
const roles = firstState.roles;
|
||||
if (services.rolesContainsUs(roles)) {
|
||||
const approveChangeRes= await services.approveChange(processId, firstState.state_id);
|
||||
const approveChangeRes = await services.approveChange(processId, firstState.state_id);
|
||||
await services.handleApiReturn(approveChangeRes);
|
||||
const prdUpdateRes = await services.createPrdUpdate(processId, firstState.state_id);
|
||||
await services.handleApiReturn(prdUpdateRes);
|
||||
@ -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;
|
||||
@ -796,7 +814,7 @@ export async function registerAllListeners() {
|
||||
// We will validate it's a MerkleProofResult in the wasm
|
||||
let parsedMerkleProof: MerkleProofResult;
|
||||
try {
|
||||
parsedMerkleProof= JSON.parse(merkleProof);
|
||||
parsedMerkleProof = JSON.parse(merkleProof);
|
||||
} catch (e) {
|
||||
throw new Error('Provided merkleProof is not a valid json object');
|
||||
}
|
||||
@ -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 || '');
|
||||
}
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
@ -20,7 +20,7 @@ self.addEventListener('message', async (event) => {
|
||||
const toDownload = await scanMissingData(myProcessesId);
|
||||
if (toDownload.length != 0) {
|
||||
console.log('Sending TO_DOWNLOAD message');
|
||||
event.source.postMessage({ type: 'TO_DOWNLOAD', data: toDownload});
|
||||
event.source.postMessage({ type: 'TO_DOWNLOAD', data: toDownload });
|
||||
}
|
||||
} else {
|
||||
event.source.postMessage({ status: 'error', message: 'Empty lists' });
|
||||
@ -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 = []
|
||||
for(const state of entry.process) {
|
||||
const filteredDiff = entry.diffs.filter(diff => diff.new_state_merkle_root === state.merkle_root);
|
||||
if(filteredDiff && filteredDiff.length) {
|
||||
diffs.push(filteredDiff)
|
||||
const diffs = [];
|
||||
for (const state of entry.process) {
|
||||
const filteredDiff = entry.diffs.filter((diff) => diff.new_state_merkle_root === state.merkle_root);
|
||||
if (filteredDiff && filteredDiff.length) {
|
||||
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) => {
|
||||
|
@ -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);
|
||||
@ -158,19 +158,19 @@ export class Database {
|
||||
|
||||
// Helper function to wait for service worker activation
|
||||
private async waitForServiceWorkerActivation(registration: ServiceWorkerRegistration): Promise<ServiceWorker | null> {
|
||||
return new Promise((resolve) => {
|
||||
return new Promise((resolve) => {
|
||||
if (registration.active) {
|
||||
resolve(registration.active);
|
||||
} else {
|
||||
const listener = () => {
|
||||
if (registration.active) {
|
||||
resolve(registration.active);
|
||||
} else {
|
||||
const listener = () => {
|
||||
if (registration.active) {
|
||||
navigator.serviceWorker.removeEventListener('controllerchange', listener);
|
||||
resolve(registration.active);
|
||||
}
|
||||
};
|
||||
navigator.serviceWorker.addEventListener('controllerchange', listener);
|
||||
navigator.serviceWorker.removeEventListener('controllerchange', listener);
|
||||
resolve(registration.active);
|
||||
}
|
||||
});
|
||||
};
|
||||
navigator.serviceWorker.addEventListener('controllerchange', listener);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async checkForUpdates() {
|
||||
@ -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', {
|
||||
detail: {
|
||||
processId,
|
||||
stateId,
|
||||
hash,
|
||||
}
|
||||
}));
|
||||
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);
|
||||
|
@ -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';
|
||||
|
@ -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');
|
||||
|
||||
@ -94,24 +94,24 @@ export default class Services {
|
||||
* Waits for at least one handshake message before returning.
|
||||
*/
|
||||
public async connectAllRelays(): Promise<void> {
|
||||
const connectedUrls: string[] = [];
|
||||
const connectedUrls: string[] = [];
|
||||
|
||||
// Connect to all relays
|
||||
for (const wsurl of Object.keys(this.relayAddresses)) {
|
||||
try {
|
||||
console.log(`Connecting to: ${wsurl}`);
|
||||
await this.addWebsocketConnection(wsurl);
|
||||
connectedUrls.push(wsurl);
|
||||
console.log(`Successfully connected to: ${wsurl}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to connect to ${wsurl}:`, error);
|
||||
}
|
||||
// Connect to all relays
|
||||
for (const wsurl of Object.keys(this.relayAddresses)) {
|
||||
try {
|
||||
console.log(`Connecting to: ${wsurl}`);
|
||||
await this.addWebsocketConnection(wsurl);
|
||||
connectedUrls.push(wsurl);
|
||||
console.log(`Successfully connected to: ${wsurl}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to connect to ${wsurl}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for at least one handshake message if we have connections
|
||||
if (connectedUrls.length > 0) {
|
||||
await this.waitForHandshakeMessage();
|
||||
}
|
||||
// Wait for at least one handshake message if we have connections
|
||||
if (connectedUrls.length > 0) {
|
||||
await this.waitForHandshakeMessage();
|
||||
}
|
||||
}
|
||||
|
||||
public async addWebsocketConnection(url: string): Promise<void> {
|
||||
@ -125,8 +125,8 @@ export default class Services {
|
||||
* @param spAddress - The SP Address (value).
|
||||
*/
|
||||
public updateRelay(wsurl: string, spAddress: string): void {
|
||||
this.relayAddresses[wsurl] = spAddress;
|
||||
console.log(`Updated: ${wsurl} -> ${spAddress}`);
|
||||
this.relayAddresses[wsurl] = spAddress;
|
||||
console.log(`Updated: ${wsurl} -> ${spAddress}`);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -135,7 +135,7 @@ export default class Services {
|
||||
* @returns The SP Address if found, or undefined if not.
|
||||
*/
|
||||
public getSpAddress(wsurl: string): string | undefined {
|
||||
return this.relayAddresses[wsurl];
|
||||
return this.relayAddresses[wsurl];
|
||||
}
|
||||
|
||||
/**
|
||||
@ -143,20 +143,20 @@ export default class Services {
|
||||
* @returns An array of objects containing wsurl and spAddress.
|
||||
*/
|
||||
public getAllRelays(): { wsurl: string; spAddress: string }[] {
|
||||
return Object.entries(this.relayAddresses).map(([wsurl, spAddress]) => ({
|
||||
wsurl,
|
||||
spAddress,
|
||||
}));
|
||||
return Object.entries(this.relayAddresses).map(([wsurl, spAddress]) => ({
|
||||
wsurl,
|
||||
spAddress,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Print all key/value pairs for debugging.
|
||||
*/
|
||||
public printAllRelays(): void {
|
||||
console.log("Current relay addresses:");
|
||||
for (const [wsurl, spAddress] of Object.entries(this.relayAddresses)) {
|
||||
console.log(`${wsurl} -> ${spAddress}`);
|
||||
}
|
||||
console.log('Current relay addresses:');
|
||||
for (const [wsurl, spAddress] of Object.entries(this.relayAddresses)) {
|
||||
console.log(`${wsurl} -> ${spAddress}`);
|
||||
}
|
||||
}
|
||||
|
||||
public isPaired(): boolean {
|
||||
@ -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);
|
||||
|
@ -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,45 +37,45 @@ 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);
|
||||
continue;
|
||||
console.error('Received response status', response.status);
|
||||
continue;
|
||||
}
|
||||
// console.log('Retrieved data:', response.data);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error('Error retrieving data:', error);
|
||||
console.error('Error retrieving data:', error);
|
||||
}
|
||||
}
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
interface TestResponse {
|
||||
key: string;
|
||||
value: boolean;
|
||||
key: string;
|
||||
value: boolean;
|
||||
}
|
||||
|
||||
export async function testData(servers: string[], key: string): Promise<Record<string, boolean | null> | null> {
|
||||
const res: Record<string, boolean | null> = {};
|
||||
for (const server of servers) {
|
||||
res[server] = null;
|
||||
try {
|
||||
const response = await axios.get(`${server}/test/${key}`);
|
||||
if (response.status !== 200) {
|
||||
console.error(`${server}: Test response status: ${response.status}`);
|
||||
continue;
|
||||
}
|
||||
const res: Record<string, boolean | null> = {};
|
||||
for (const server of servers) {
|
||||
res[server] = null;
|
||||
try {
|
||||
const response = await axios.get(`${server}/test/${key}`);
|
||||
if (response.status !== 200) {
|
||||
console.error(`${server}: Test response status: ${response.status}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const data: TestResponse = response.data;
|
||||
const data: TestResponse = response.data;
|
||||
|
||||
res[server] = data.value;
|
||||
} catch (error) {
|
||||
console.error('Error retrieving data:', error);
|
||||
return null;
|
||||
}
|
||||
res[server] = data.value;
|
||||
} catch (error) {
|
||||
console.error('Error retrieving data:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
return res;
|
||||
}
|
||||
|
@ -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) {
|
||||
|
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' {
|
||||
// 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;
|
||||
|
@ -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> = {};
|
||||
|
||||
|
@ -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;
|
||||
@ -155,7 +155,7 @@ async function onCreateButtonClick() {
|
||||
const service = await Services.getInstance();
|
||||
await service.confirmPairing();
|
||||
} catch (e) {
|
||||
console.error(`onCreateButtonClick error: ${e}`);
|
||||
console.error(`onCreateButtonClick error: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
@ -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');
|
||||
@ -202,9 +198,9 @@ export async function generateQRCode(spAddress: string) {
|
||||
}
|
||||
|
||||
export async function generateCreateBtn() {
|
||||
try{
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user