chore: align relay bootstrap configuration

**Motivations :**
- document and enforce the secure websocket endpoint for the relay
- streamline wallet setup flow without manual blockers

**Modifications :**
- update docs and service bootstrap logic to rely on VITE_BOOTSTRAPURL with explicit /ws suffix
- clean wallet setup and block sync pages to run automatically without continue buttons
- refresh shared styles and services to match the new initialization path and logging adjustments

**Page affectées :**
- docs/INTEGRATION.md
- src/services/service.ts
- src/pages/wallet-setup/wallet-setup.*
This commit is contained in:
NicolasCantu 2025-10-31 13:46:59 +01:00
parent 44adae2d05
commit 274b19e410
26 changed files with 4345 additions and 6078 deletions

View File

@ -4,4 +4,5 @@ alwaysApply: true
le site tourne sur le port 3004
l'url du site est https://dev3.4nkweb.com
ne déclanche jamais la CI
ne déclanche jamais la CI
le relai doit tourner sur 8091

2
.gitignore vendored
View File

@ -99,3 +99,5 @@ error.log
.netlify/
firebase/
functions/lib/
sdk_relay
sdk_client

View File

@ -71,6 +71,11 @@ src/
- **Storage**: IndexedDB, Service Workers
- **Communication**: WebSockets, PostMessage API
### **WebSocket Relay Configuration**
- Default relay runs locally on `127.0.0.1:8091` and is exposed securely via `wss://relay235.4nkweb.com`
- Nginx TLS termination is defined in `nginx.relay235.conf` (kept alongside the existing `nginx.dev.conf`)
- Clients must configure `VITE_BOOTSTRAPURL=wss://relay235.4nkweb.com` to avoid mixed-content issues when the app is served over HTTPS
## 🔧 Développement
### **Standards de code**

View File

@ -18,6 +18,8 @@ Le système IHM_CLIENT suit un processus d'initialisation en plusieurs étapes p
- **`diffs`** : Stockage des différences de synchronisation
- **`data`** : Stockage des données générales
> Note: The IndexedDB stores are provisioned from the shared `DATABASE_CONFIG` for both the main thread database helper and the `database.worker.js`, ensuring that `credentials` and `env` collections are always created before the pairing flow starts.
## Flux d'Initialisation Complet
### 1. Démarrage de l'Application

View File

@ -108,6 +108,11 @@ Les styles s'adaptent automatiquement :
<iframe src="https://your-4nk-site.com" width="100%" height="600px"></iframe>
```
### 1.1 Relai WebSocket
- Relai principal exposé en `wss://relay235.4nkweb.com`
- Terminaison TLS gérée par `nginx.relay235.conf` (reverse proxy vers le service local sur `127.0.0.1:8091`)
- Variables denvironnement cliente à utiliser : `VITE_BOOTSTRAPURL=wss://relay235.4nkweb.com`
### 2. Intégration personnalisée
```html
<!-- Site externe -->

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,597 +1,522 @@
/* Styles de base */
:root {
--primary-color: #3A506B;
/* Bleu métallique */
--secondary-color: #B0BEC5;
/* Gris acier */
--accent-color: #D68C45;
/* Cuivre */
}
/* Chat page base */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
margin: 0;
min-height: 100vh;
background: #f3f5f9;
color: var(--color-text-primary);
font-family: 'Inter', 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
display: flex;
flex-direction: column;
}
a {
color: inherit;
text-decoration: none;
}
/* 4NK NAVBAR */
/* Navigation */
.nav-wrapper {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 70px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 24px;
background: linear-gradient(135deg, rgba(255, 255, 255, 0.96), rgba(232, 238, 244, 0.9));
box-shadow: 0 12px 28px rgba(15, 23, 42, 0.14);
z-index: 25;
backdrop-filter: blur(10px);
}
.brand-logo {
text-align: center;
font-size: 1.5em;
font-weight: bold;
font-size: 1.4rem;
font-weight: 700;
color: var(--color-primary);
}
.nav-wrapper {
position: fixed;
background: radial-gradient(circle, white, var(--primary-color));
display: flex;
justify-content: space-between;
align-items: center;
color: #37474F;
height: 9vh;
width: 100vw;
left: 0;
top: 0;
box-shadow: 0px 8px 10px -5px rgba(0, 0, 0, .2), 0px 16px 24px 2px rgba(0, 0, 0, .14), 0px 6px 30px 5px rgba(0, 0, 0, .12);
}
/* Icônes de la barre de navigation */
.nav-right-icons {
display: flex;
display: inline-flex;
align-items: center;
gap: 18px;
}
.notification-container {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
}
.notification-bell,
.burger-menu {
height: 20px;
width: 20px;
margin-right: 1rem;
cursor: pointer;
width: 22px;
height: 22px;
display: inline-flex;
align-items: center;
justify-content: center;
color: var(--color-text-secondary);
cursor: pointer;
transition: color var(--transition-base);
}
.notification-container {
position: relative;
/* Conserve la position pour le notification-board */
display: inline-flex;
align-items: center;
}
.notification-board {
position: absolute;
/* Position absolue pour le placer par rapport au container */
top: 40px;
right: 0;
background-color: white;
border: 1px solid #ccc;
padding: 10px;
width: 200px;
max-height: 300px;
overflow-y: auto;
/* Scroll si les notifications dépassent la taille */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
z-index: 10;
/* Définit la priorité d'affichage au-dessus des autres éléments */
display: none;
/* Par défaut, la notification est masquée */
}
.notification-item{
cursor: pointer;
.notification-bell:hover,
.burger-menu:hover {
color: var(--color-primary);
}
.notification-badge {
position: absolute;
top: -18px;
right: 35px;
background-color: red;
color: white;
border-radius: 50%;
padding: 4px 8px;
font-size: 12px;
display: none;
/* S'affiche seulement lorsqu'il y a des notifications */
z-index: 10;
position: absolute;
top: -6px;
right: -6px;
min-width: 18px;
height: 18px;
padding: 0 6px;
border-radius: 999px;
background: var(--color-danger);
color: #fff;
font-size: 0.7rem;
font-weight: 700;
display: none;
}
/* Par défaut, le menu est masqué */
#menu {
display: none;
/* Menu caché par défaut */
transition: display 0.3s ease-in-out;
.notification-badge.is-visible {
display: inline-flex;
align-items: center;
justify-content: center;
}
.burger-menu {
cursor: pointer;
.notification-board {
position: absolute;
top: calc(100% + 12px);
right: 0;
width: min(280px, 90vw);
background: var(--color-surface);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-lg);
border: 1px solid rgba(148, 163, 184, 0.22);
padding: 10px 0;
display: none;
flex-direction: column;
z-index: 40;
}
/* Icône burger */
#burger-icon {
cursor: pointer;
.notification-board.is-visible {
display: flex;
}
.menu-content {
display: none;
position: absolute;
top: 3.4rem;
right: 1rem;
background-color: white;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
border-radius: 5px;
overflow: hidden;
.notification-board .notification-item,
.notification-board .notification-element {
padding: 10px 16px;
color: var(--color-text-primary);
transition: background var(--transition-base);
}
.menu-content a {
display: block;
padding: 10px 20px;
text-decoration: none;
color: #333;
border-bottom: 1px solid #e0e0e0;
&:hover {
background-color: rgba(26, 28, 24, .08);
}
.notification-board .notification-item:hover,
.notification-board .notification-element:hover {
background: rgba(58, 80, 107, 0.1);
}
.menu-content a:last-child {
border-bottom: none;
}
/* Ajustement pour la barre de navigation fixe */
/* Layout */
.container {
display: flex;
flex: 1;
height: 90vh;
margin-top: 9vh;
margin-left: -1%;
text-align: left;
width: 100vw;
margin-top: 90px;
display: grid;
grid-template-columns: clamp(220px, 22%, 280px) minmax(0, 1fr);
gap: 20px;
padding: 24px 32px 48px;
box-sizing: border-box;
}
/* Liste des groupes */
.group-list {
width: 25%;
background-color: #1f2c3d;
color: white;
padding: 20px;
box-sizing: border-box;
overflow-y: auto;
border-right: 2px solid #2c3e50;
flex-shrink: 0;
padding-right: 10px;
height: 91vh;
background: linear-gradient(180deg, #1f2c3d, #1b2735);
color: #fff;
border-radius: var(--radius-lg);
padding: 22px 18px;
display: flex;
flex-direction: column;
gap: 16px;
box-shadow: var(--shadow-sm);
height: calc(100vh - 136px);
overflow-y: auto;
}
.group-list ul {
cursor: pointer;
list-style: none;
padding: 0;
padding-right: 10px;
margin-left: 20px;
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 12px;
}
.group-list li {
margin-bottom: 20px;
padding: 15px;
border-radius: 8px;
background-color: #273646;
cursor: pointer;
transition: background-color 0.3s, box-shadow 0.3s;
background: rgba(255, 255, 255, 0.08);
border-radius: var(--radius-md);
padding: 14px 16px;
transition: transform var(--transition-base), background var(--transition-base), box-shadow var(--transition-base);
cursor: pointer;
}
.group-list li:hover {
background-color: #34495e;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
.group-list li:hover,
.group-list li.active {
background: rgba(255, 255, 255, 0.18);
transform: translateX(4px);
box-shadow: 0 14px 24px rgba(0, 0, 0, 0.2);
}
.group-list .member-container {
position: relative;
.member-container {
position: relative;
}
.group-list .member-container button {
margin-left: 40px;
padding: 5px;
cursor: pointer;
background: var(--primary-color);
color: white;
border: 0px solid var(--primary-color);
border-radius: 50px;
position: absolute;
top: -25px;
right: -25px;
.member-container button {
position: absolute;
top: -16px;
right: -16px;
padding: 6px 12px;
border-radius: 999px;
border: none;
font-size: 0.75rem;
font-weight: 600;
background: var(--color-primary);
color: #fff;
cursor: pointer;
transition: background var(--transition-base);
}
.group-list .member-container button:hover {
background: var(--accent-color)
.member-container button:hover {
background: var(--color-accent);
}
/* Zone de chat */
.chat-area {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
background-color:#f1f1f1;
border-radius: 10px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
margin: 1% 0% 0.5% 1%;
/* Chat area */
.chat-area,
.signature-area {
background: var(--color-surface);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-md);
display: flex;
flex-direction: column;
gap: 16px;
padding: 20px;
min-height: calc(100vh - 136px);
}
/* En-tête du chat */
.chat-header {
background-color: #34495e;
color: white;
padding: 15px;
font-size: 20px;
font-weight: bold;
border-radius: 10px 10px 0 0;
text-align: center;
.chat-header,
.signature-header {
background: var(--color-primary);
color: #fff;
border-radius: var(--radius-md);
padding: 14px 18px;
font-weight: 600;
font-size: 1.1rem;
text-align: center;
}
/* Messages */
.messages {
flex: 1;
padding: 20px;
overflow-y: auto;
background-color: #f1f1f1;
border-top: 1px solid #ddd;
flex: 1;
overflow-y: auto;
padding: 18px;
display: flex;
flex-direction: column;
gap: 12px;
background: rgba(58, 80, 107, 0.04);
border-radius: var(--radius-md);
border: 1px solid rgba(148, 163, 184, 0.25);
}
.message-container {
display: flex;
margin: 8px;
}
.message-container .message {
align-self: flex-start;
}
.message-container .message.user {
align-self: flex-end;
margin-left: auto;
color: white;
display: flex;
}
.message {
max-width: 70%;
padding: 10px;
border-radius: 12px;
background:var(--secondary-color);
margin: 2px 0;
max-width: 68%;
padding: 10px 14px;
border-radius: var(--radius-lg);
background: var(--color-secondary);
color: var(--color-text-primary);
box-shadow: 0 8px 16px rgba(15, 23, 42, 0.12);
position: relative;
display: inline-flex;
flex-direction: column;
gap: 6px;
}
/* Messages de l'utilisateur */
.message.user {
background: #2196f3;
color: white;
margin-left: auto;
background: linear-gradient(135deg, #2196f3, #1363b5);
color: #fff;
}
.message-time {
font-size: 0.7em;
opacity: 0.7;
margin-left: 0px;
margin-top: 5px;
font-size: 0.75rem;
opacity: 0.7;
align-self: flex-end;
}
/* Amélioration de l'esthétique des messages */
/* .message.user:before {
content: '';
position: absolute;
top: 10px;
right: -10px;
border: 10px solid transparent;
border-left-color: #3498db;
} */
/* Zone de saisie */
.input-area {
padding: 10px;
background-color: #bdc3c7;
display: flex;
align-items: center;
border-radius: 10px;
margin: 1%;
/* Alignement vertical */
display: flex;
align-items: center;
gap: 12px;
padding: 12px;
border-radius: var(--radius-md);
background: rgba(148, 163, 184, 0.18);
}
.input-area input[type="text"] {
flex: 1;
/* Prend l'espace restant */
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
.input-area input[type='text'] {
flex: 1;
border: 1px solid rgba(148, 163, 184, 0.4);
border-radius: var(--radius-md);
padding: 10px 12px;
font-size: 0.95rem;
}
.input-area .attachment-icon {
margin: 0 10px;
cursor: pointer;
display: flex;
align-items: center;
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border-radius: 50%;
background: rgba(58, 80, 107, 0.12);
color: var(--color-primary);
cursor: pointer;
}
.input-area button {
padding: 10px;
margin-left: 10px;
background-color: #2980b9;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
padding: 10px 18px;
border: none;
border-radius: var(--radius-md);
background: linear-gradient(135deg, #2980b9, #1f608d);
color: #fff;
font-weight: 600;
cursor: pointer;
transition: transform var(--transition-base), box-shadow var(--transition-base);
}
.input-area button:hover {
background-color: #1f608d;
transform: translateY(-1px);
box-shadow: 0 12px 22px rgba(41, 128, 185, 0.35);
}
.tabs {
display: flex;
margin: 20px 0px;
gap: 10px;
display: inline-flex;
gap: 10px;
}
.tabs button {
padding: 10px 20px;
cursor: pointer;
background: var(--primary-color);
color: white;
border: 0px solid var(--primary-color);
margin-right: 5px;
border-radius: 10px;
padding: 8px 16px;
border-radius: var(--radius-md);
border: none;
background: var(--color-primary);
color: #fff;
font-weight: 600;
cursor: pointer;
transition: transform var(--transition-base), box-shadow var(--transition-base);
}
.tabs button:hover {
background: var(--secondary-color);
color: var(--primary-color);
transform: translateY(-1px);
box-shadow: 0 10px 18px rgba(58, 80, 107, 0.25);
}
/* Signature */
.signature-area {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
background-color:#f1f1f1;
border-radius: 10px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
margin: 1% 0% 0.5% 1%;
transition: all 1s ease 0.1s;
visibility: visible;
gap: 18px;
transition: opacity 0.3s ease;
}
.signature-area.hidden {
opacity: 0;
visibility: hidden;
display: none;
pointer-events: none;
}
.signature-header {
display: flex;
align-items: center;
justify-content: center;
background-color: var(--primary-color);
color: white;
border-radius: 10px 10px 0 0;
padding-left: 4%;
display: none !important;
}
.signature-content {
padding: 10px;
background-color: var(--secondary-color);
color: var(--primary-color);
height: 100%;
border-radius: 10px;
margin: 1%;
display: flex;
flex-direction: column;
align-items: center;
background: rgba(58, 80, 107, 0.08);
color: var(--color-text-primary);
border-radius: var(--radius-md);
padding: 16px;
display: flex;
flex-direction: column;
gap: 14px;
}
.signature-description {
height: 20%;
width: 100%;
margin: 0% 10% 0% 10%;
overflow: auto;
display: flex;
.signature-description,
.signature-documents {
display: flex;
gap: 12px;
overflow-x: auto;
padding-bottom: 6px;
}
.signature-description li {
margin: 1% 0% 1% 0%;
list-style: none;
padding: 2%;
border-radius: 10px;
background-color: var(--primary-color);
color: var(--secondary-color);
width: 20%;
text-align: center;
cursor: pointer;
font-weight: bold;
margin-right: 2%;
overflow: auto;
list-style: none;
padding: 10px 12px;
border-radius: var(--radius-md);
background: var(--color-primary);
color: #fff;
min-width: 140px;
text-align: center;
cursor: pointer;
transition: transform var(--transition-base), background var(--transition-base);
}
.signature-description li .member-list {
margin-left: -30%;
.signature-description li:hover {
background: var(--color-accent);
transform: translateY(-2px);
}
.signature-description li .member-list li {
width: 100%;
.new-request-btn,
#request-document-button,
.sign-button {
padding: 10px 18px;
border-radius: var(--radius-md);
border: none;
background: linear-gradient(135deg, var(--color-success), #2e7d32);
color: #fff;
font-weight: 600;
cursor: pointer;
transition: transform var(--transition-base), box-shadow var(--transition-base);
}
.signature-description li .member-list li:hover {
background-color: var(--secondary-color);
color: var(--primary-color);
.new-request-btn:hover,
#request-document-button:hover,
.sign-button:hover {
transform: translateY(-1px);
box-shadow: 0 12px 24px rgba(76, 175, 80, 0.32);
}
.signature-documents {
height: 80%;
width: 100%;
margin: 0% 10% 0% 10%;
overflow: auto;
display: flex;
/* Modals */
.modal,
.notifications-modal,
.qr-modal,
.request-modal,
.modal-document,
.pairing-modal {
position: fixed;
inset: 0;
background: rgba(15, 23, 42, 0.55);
display: none;
align-items: center;
justify-content: center;
backdrop-filter: blur(10px);
z-index: 60;
padding: 24px;
box-sizing: border-box;
}
.signature-documents-header {
display: flex;
width: 100%;
height: 15%;
align-items: center;
.modal.is-visible,
.notifications-modal.is-visible,
.qr-modal.is-visible,
.request-modal.is-visible,
.modal-document.is-visible,
.pairing-modal.is-visible {
display: flex;
}
#request-document-button {
background-color: var(--primary-color);
color: white;
border: none;
border-radius: 10px;
padding: 8px;
cursor: pointer;
margin-left: 5%;
font-weight: bold;
.modal-content,
.notifications-content,
.qr-modal-content,
.request-modal .modal-content,
.modal-document .modal-content,
.pairing-modal-content {
background: var(--color-surface);
border-radius: var(--radius-lg);
padding: 24px;
width: min(480px, 100%);
max-height: 80vh;
overflow-y: auto;
box-shadow: var(--shadow-lg);
position: relative;
display: flex;
flex-direction: column;
gap: 16px;
}
#request-document-button:hover {
background-color: var(--accent-color);
font-weight: bold;
.close-modal,
.close-button,
.close-qr-modal,
.close-signature,
.close-contract-popup {
position: absolute;
top: 14px;
right: 14px;
border: none;
background: transparent;
font-size: 1.4rem;
color: var(--color-text-secondary);
cursor: pointer;
}
#close-signature {
cursor: pointer;
align-items: center;
margin-left: auto;
margin-right: 2%;
border-radius: 50%;
background-color: var(--primary-color);
color: white;
border: none;
padding: -3%;
margin-top: -5%;
font-size: 1em;
font-weight: bold;
}
#close-signature:hover {
background-color: var(--secondary-color);
color: var(--primary-color);
}
/* REQUEST MODAL */
.request-modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
.close-modal:hover,
.close-button:hover,
.close-qr-modal:hover,
.close-signature:hover,
.close-contract-popup:hover {
color: var(--color-primary);
}
.modal-content {
background-color: var(--secondary-color);
padding: 20px;
border-radius: 8px;
position: relative;
min-width: 300px;
}
.close-modal {
position: absolute;
top: 10px;
right: 10px;
border: none;
background: none;
font-size: 1.5em;
cursor: pointer;
font-weight: bold;
}
.close-modal:hover {
color: var(--accent-color);
}
.modal-members {
display: flex;
justify-content: space-between;
}
.modal-members ul li{
list-style: none;
}
.file-upload-container {
margin: 10px 0;
}
.file-list {
margin-top: 10px;
}
.file-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 5px;
margin: 5px 0;
background: var(--background-color-secondary);
border-radius: 4px;
}
.remove-file {
background: none;
border: none;
color: var(--text-color);
cursor: pointer;
padding: 0 5px;
}
.remove-file:hover {
color: var(--error-color);
}
#message-input {
width: 100%;
height: 50px;
resize: none;
padding: 10px;
box-sizing: border-box;
overflow: auto;
max-width: 100%;
border-radius: 10px;
.modal-footer,
.button-group,
.header-buttons {
display: flex;
justify-content: flex-end;
gap: 12px;
}
/* Responsive */
@media screen and (max-width: 768px) {
.group-list {
display: none;
/* Masquer la liste des groupes sur les petits écrans */
}
@media (max-width: 1024px) {
.container {
grid-template-columns: 1fr;
padding: 18px 18px 36px;
}
.chat-area {
margin: 0;
}
.group-list {
height: auto;
max-height: none;
}
}
@media (max-width: 768px) {
.nav-wrapper {
height: auto;
flex-direction: column;
align-items: flex-start;
gap: 8px;
padding: 14px 18px;
}
::-webkit-scrollbar {
width: 5px;
height: 5px;
.nav-right-icons {
align-self: flex-end;
}
.container {
padding: 16px 14px 32px;
}
.chat-area,
.signature-area {
min-height: auto;
}
}
::-webkit-scrollbar-track {
background: var(--primary-color);
border-radius: 5px;
}
@media (max-width: 480px) {
.message {
max-width: 85%;
}
::-webkit-scrollbar-thumb {
background: var(--secondary-color);
border-radius: 5px;
}
.input-area {
flex-direction: column;
align-items: stretch;
}
::-webkit-scrollbar-thumb:hover {
background: var(--accent-color);
.input-area button {
width: 100%;
}
.tabs {
flex-wrap: wrap;
}
.tabs button {
width: 100%;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -355,7 +355,7 @@ export class SecureCredentialsComponent {
/**
* Gère l'événement de création de credentials
*/
private handleCredentialsCreated(data: any): void {
private handleCredentialsCreated(_data: any): void {
secureLogger.info('Credentials created', { component: 'SecureCredentials' });
this.showMessage('Credentials créés avec succès !', 'success');
this.updateUI();

View File

@ -74,29 +74,6 @@
width: 0%;
transition: width 0.3s ease;
}
.continue-btn {
width: 100%;
background: #667eea;
color: white;
border: none;
border-radius: 8px;
padding: 15px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
margin-top: 20px;
transition: background 0.3s ease;
}
.continue-btn:hover {
background: #5a6fd8;
}
.continue-btn:disabled {
background: #ccc;
cursor: not-allowed;
}
</style>
</head>
<body>
@ -111,8 +88,6 @@
<div class="progress">
<div class="progress-bar" id="progressBar"></div>
</div>
<button class="continue-btn" id="continueBtn" disabled>Synchroniser les blocs</button>
</div>
<script type="module" src="./birthday-setup.ts"></script>

View File

@ -178,11 +178,21 @@ document.addEventListener('DOMContentLoaded', async () => {
const status = document.getElementById('status') as HTMLDivElement;
const progressBar = document.getElementById('progressBar') as HTMLDivElement;
const continueBtn = document.getElementById('continueBtn') as HTMLButtonElement;
let lastStatusMessage = '';
let lastStatusType: 'loading' | 'success' | 'error' | null = null;
function updateStatus(message: string, type: 'loading' | 'success' | 'error') {
if (lastStatusMessage === message && lastStatusType === type) {
return;
}
lastStatusMessage = message;
lastStatusType = type;
status.textContent = message;
status.className = `status ${type}`;
status.setAttribute('data-status', type);
}
function updateProgress(percent: number) {
@ -228,14 +238,4 @@ document.addEventListener('DOMContentLoaded', async () => {
isInitializing = false;
}
// Gestion du bouton continuer
continueBtn.addEventListener('click', async () => {
secureLogger.info('🏠 Redirecting to main application...', { component: 'BirthdaySetup' });
// Rediriger vers l'application principale
secureLogger.debug('🎂 Birthday setup completed, checking storage state...', {
component: 'BirthdaySetup',
});
const { checkStorageStateAndNavigate } = await import('../../router');
await checkStorageStateAndNavigate();
});
});

View File

@ -125,29 +125,6 @@
.sync-status.error {
color: #dc3545;
}
.continue-btn {
width: 100%;
background: #667eea;
color: white;
border: none;
border-radius: 8px;
padding: 15px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
margin-top: 20px;
transition: background 0.3s ease;
}
.continue-btn:hover:not(:disabled) {
background: #5a6fd8;
}
.continue-btn:disabled {
background: #ccc;
cursor: not-allowed;
}
</style>
</head>
<body>
@ -187,7 +164,7 @@
</div>
</div>
</div>
<script type="module" src="./block-sync.ts"></script>

View File

@ -182,7 +182,14 @@ document.addEventListener('DOMContentLoaded', async () => {
const originalConsoleLog = console.log;
console.log = (...args: any[]) => {
const message = args.join(' ');
if (message.includes('Scan progress:')) {
const containsProgress = message.includes('Scan progress:');
secureLogger.debug('SDK console output intercepted', {
component: 'BlockSync',
containsProgress
});
if (containsProgress) {
// Extraire les informations de progression
const progressMatch = message.match(/Scan progress: (\d+)\/(\d+) \((\d+)%\)/);
if (progressMatch) {
@ -201,7 +208,12 @@ document.addEventListener('DOMContentLoaded', async () => {
updateSyncItem('blocksScanned', currentBlock.toString(), 'pending');
updateSyncItem('blocksToScan', (totalBlocks - currentBlock).toString(), 'pending');
// Progress message available if needed: `Bloc ${currentBlock}/${totalBlocks} (${percentage}%)`
secureLogger.debug('SDK progress update parsed', {
component: 'BlockSync',
currentBlock,
totalBlocks,
percentage
});
}
}
// Appeler la fonction console.log originale

View File

@ -34,6 +34,7 @@
<script type="module">
import { MessageType } from '../models/process.model';
import IframePairingService from '../services/iframe-pairing.service';
import { secureLogger } from '../services/secure-logger';
// Initialize the iframe pairing service
const pairingService = IframePairingService.getInstance();
@ -44,11 +45,16 @@
switch (type) {
case MessageType.PAIRING_4WORDS_CREATE:
console.log('🔐 Parent requested pairing creation');
secureLogger.info('Parent requested pairing creation', {
component: 'IframePairingPage'
});
pairingService.createPairing();
break;
case MessageType.PAIRING_4WORDS_JOIN:
console.log('🔗 Parent requested pairing join with words:', data.words);
secureLogger.info('Parent requested pairing join', {
component: 'IframePairingPage',
hasWords: Boolean(data?.words)
});
pairingService.joinPairing(data.words);
break;
}
@ -63,7 +69,9 @@
'*'
);
console.log('🔗 Hidden iframe pairing service ready');
secureLogger.info('Hidden iframe pairing service ready', {
component: 'IframePairingPage'
});
</script>
</body>
</html>

View File

@ -74,29 +74,6 @@
width: 0%;
transition: width 0.3s ease;
}
.continue-btn {
width: 100%;
background: #667eea;
color: white;
border: none;
border-radius: 8px;
padding: 15px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
margin-top: 20px;
transition: background 0.3s ease;
}
.continue-btn:hover {
background: #5a6fd8;
}
.continue-btn:disabled {
background: #ccc;
cursor: not-allowed;
}
</style>
</head>
<body>
@ -111,8 +88,6 @@
<div class="progress">
<div class="progress-bar" id="progressBar"></div>
</div>
</div>
<script type="module" src="./wallet-setup.ts"></script>

View File

@ -14,9 +14,20 @@ document.addEventListener('DOMContentLoaded', async () => {
const progressBar = document.getElementById('progressBar') as HTMLDivElement;
const continueBtn = document.getElementById('continueBtn') as HTMLButtonElement | null;
let lastStatusMessage = '';
let lastStatusType: 'loading' | 'success' | 'error' | null = null;
function updateStatus(message: string, type: 'loading' | 'success' | 'error') {
if (lastStatusMessage === message && lastStatusType === type) {
return;
}
lastStatusMessage = message;
lastStatusType = type;
status.textContent = message;
status.className = `status ${type}`;
status.setAttribute('data-status', type);
}
function updateProgress(percent: number) {
@ -521,10 +532,12 @@ document.addEventListener('DOMContentLoaded', async () => {
}
// Gestion du bouton continuer
continueBtn.addEventListener('click', async () => {
if (continueBtn) {
continueBtn.addEventListener('click', async () => {
secureLogger.info('🔗 Redirecting to birthday setup...', { component: 'WalletSetup' });
secureLogger.info('💰 Wallet setup completed, redirecting to birthday configuration...', { component: 'WalletSetup' });
// Rediriger directement vers la page de configuration de la date anniversaire
window.location.href = '/src/pages/birthday-setup/birthday-setup.html';
});
});
}
});

View File

@ -21,7 +21,7 @@ const routes: { [key: string]: string } = {
'wallet-setup': '/src/pages/wallet-setup/wallet-setup.html',
'birthday-setup': '/src/pages/birthday-setup/birthday-setup.html',
'block-sync': '/src/pages/block-sync/block-sync.html',
'pairing': '/src/pages/pairing/pairing.html',
pairing: '/src/pages/pairing/pairing.html',
};
export let currentRoute = '';
@ -37,7 +37,9 @@ export let currentRoute = '';
* - Sinon security-setup
*/
export async function checkStorageStateAndNavigate(): Promise<void> {
secureLogger.debug('🔍 Checking storage state to determine next step...', { component: 'Router' });
secureLogger.debug('🔍 Checking storage state to determine next step...', {
component: 'Router',
});
try {
// Utiliser DeviceReaderService pour éviter d'initialiser WebAssembly
@ -49,7 +51,9 @@ export async function checkStorageStateAndNavigate(): Promise<void> {
if (!pbkdf2KeyResult) {
// Aucune clé PBKDF2 trouvée, commencer par la configuration de sécurité
secureLogger.info('🔐 No PBKDF2 key found, navigating to security-setup', { component: 'Router' });
secureLogger.info('🔐 No PBKDF2 key found, navigating to security-setup', {
component: 'Router',
});
await navigate('security-setup');
return;
}
@ -57,24 +61,29 @@ export async function checkStorageStateAndNavigate(): Promise<void> {
// Vérifier si le wallet existe (même avec birthday = 0)
const device = await deviceReader.getDeviceFromDatabase();
if (!device?.sp_wallet) {
secureLogger.info('💰 Wallet does not exist, navigating to wallet-setup', { component: 'Router' });
secureLogger.info('💰 Wallet does not exist, navigating to wallet-setup', {
component: 'Router',
});
await navigate('wallet-setup');
return;
}
// Vérifier si la date anniversaire est configurée (wallet avec birthday > 0)
if (device.sp_wallet.birthday && device.sp_wallet.birthday > 0) {
secureLogger.info('🎂 Birthday is configured, navigating to pairing', { component: 'Router' });
secureLogger.info('🎂 Birthday is configured, navigating to pairing', {
component: 'Router',
});
// Rediriger vers la page de pairing standalone
await navigate('pairing');
return;
}
// Wallet existe mais birthday pas configuré
secureLogger.info('💰 Wallet exists but birthday not set, navigating to birthday-setup', { component: 'Router' });
secureLogger.info('💰 Wallet exists but birthday not set, navigating to birthday-setup', {
component: 'Router',
});
await navigate('birthday-setup');
return;
} catch (error) {
secureLogger.error('❌ Error checking storage state:', error, { component: 'Router' });
// En cas d'erreur, commencer par la configuration de sécurité
@ -112,7 +121,13 @@ async function handleLocation(path: string) {
secureLogger.info('📍 Route HTML:', { component: 'Router', data: routeHtml });
// Pour les pages de setup, rediriger directement vers la page HTML
if (path === 'security-setup' || path === 'wallet-setup' || path === 'birthday-setup' || path === 'block-sync' || path === 'pairing') {
if (
path === 'security-setup' ||
path === 'wallet-setup' ||
path === 'birthday-setup' ||
path === 'block-sync' ||
path === 'pairing'
) {
secureLogger.info('📍 Processing setup route:', { component: 'Router', data: path });
window.location.href = routeHtml;
return;
@ -161,13 +176,17 @@ async function handleLocation(path: string) {
switch (path) {
case 'process':
// Process functionality removed - redirect to account
secureLogger.warn('Process functionality has been removed, redirecting to account', { component: 'Router' });
secureLogger.warn('Process functionality has been removed, redirecting to account', {
component: 'Router',
});
await navigate('account');
break;
case 'process-element':
// Process element functionality removed
secureLogger.warn('Process element functionality has been removed', { component: 'Router' });
secureLogger.warn('Process element functionality has been removed', {
component: 'Router',
});
break;
case 'account':
@ -217,17 +236,23 @@ export async function init(): Promise<void> {
// Vérifier l'état du storage et naviguer vers la page appropriée
// Cette fonction est maintenant légère et ne nécessite pas WebAssembly
secureLogger.debug('🔍 Checking storage state and navigating to appropriate page...', { component: 'Router' });
secureLogger.debug('🔍 Checking storage state and navigating to appropriate page...', {
component: 'Router',
});
await checkStorageStateAndNavigate();
secureLogger.info('✅ Application initialization completed successfully', { component: 'Router' });
secureLogger.info('✅ Application initialization completed successfully', {
component: 'Router',
});
} catch (error) {
secureLogger.error('❌ Application initialization failed:', error, { component: 'Router' });
// Handle WebAssembly memory errors specifically
if (error instanceof RangeError && error.message.includes('WebAssembly.instantiate')) {
secureLogger.error('🚨 WebAssembly memory error detected', { component: 'Router' });
secureLogger.info('💡 Try refreshing the page or closing other tabs to free memory', { component: 'Router' });
secureLogger.info('💡 Try refreshing the page or closing other tabs to free memory', {
component: 'Router',
});
// Show user-friendly error message
alert('⚠️ Insufficient memory for WebAssembly. Please refresh the page or close other tabs.');
@ -335,7 +360,10 @@ export async function registerAllListeners() {
secureLogger.info('🧱 Creating pairing process...', { component: 'Router' });
const createPairingProcessReturn = await services.createPairingProcess('', [myAddress]);
secureLogger.info('🧾 Pairing process created:', { component: 'Router', data: createPairingProcessReturn });
secureLogger.info('🧾 Pairing process created:', {
component: 'Router',
data: createPairingProcessReturn,
});
const pairingId = createPairingProcessReturn.updated_process?.process_id;
const stateId = createPairingProcessReturn.updated_process?.current_process?.states[0]
@ -347,32 +375,51 @@ export async function registerAllListeners() {
secureLogger.info('🔒 Registering device as paired...', { component: 'Router' });
services.pairDevice(pairingId, [myAddress]);
secureLogger.info('🧠 Handling API return for createPairingProcess...', { component: 'Router' });
secureLogger.info('🧠 Handling API return for createPairingProcess...', {
component: 'Router',
});
await services.handleApiReturn(createPairingProcessReturn);
secureLogger.debug('🔍 DEBUG: About to create PRD update...', { component: 'Router' });
secureLogger.info('🧰 Creating PRD update...', { component: 'Router' });
const createPrdUpdateReturn = await services.createPrdUpdate(pairingId, stateId);
secureLogger.info('🧾 PRD update result:', { component: 'Router', data: createPrdUpdateReturn });
secureLogger.info('🧾 PRD update result:', {
component: 'Router',
data: createPrdUpdateReturn,
});
await services.handleApiReturn(createPrdUpdateReturn);
secureLogger.debug('✅ DEBUG: PRD update completed successfully!', { component: 'Router' });
secureLogger.debug('🔍 DEBUG: About to approve change...', { component: 'Router' });
secureLogger.info('✅ Approving change...', { component: 'Router' });
const approveChangeReturn = await services.approveChange(pairingId, stateId);
secureLogger.info('📜 Approve change result:', { component: 'Router', data: approveChangeReturn });
secureLogger.info('📜 Approve change result:', {
component: 'Router',
data: approveChangeReturn,
});
await services.handleApiReturn(approveChangeReturn);
secureLogger.debug('✅ DEBUG: approveChange completed successfully!', { component: 'Router' });
secureLogger.debug('✅ DEBUG: approveChange completed successfully!', {
component: 'Router',
});
secureLogger.debug('🔍 DEBUG: approveChange completed, about to call waitForPairingCommitment...', { component: 'Router' });
secureLogger.info('⏳ Waiting for pairing process to be committed...', { component: 'Router' });
secureLogger.debug(
'🔍 DEBUG: approveChange completed, about to call waitForPairingCommitment...',
{ component: 'Router' }
);
secureLogger.info('⏳ Waiting for pairing process to be committed...', {
component: 'Router',
});
await services.waitForPairingCommitment(pairingId);
secureLogger.debug('✅ DEBUG: waitForPairingCommitment completed successfully!', { component: 'Router' });
secureLogger.debug('✅ DEBUG: waitForPairingCommitment completed successfully!', {
component: 'Router',
});
secureLogger.debug('🔍 DEBUG: About to call confirmPairing...', { component: 'Router' });
secureLogger.info('🔁 Confirming pairing...', { component: 'Router' });
await services.confirmPairing(pairingId);
secureLogger.debug('✅ DEBUG: confirmPairing completed successfully!', { component: 'Router' });
secureLogger.debug('✅ DEBUG: confirmPairing completed successfully!', {
component: 'Router',
});
secureLogger.info('🎉 Pairing successfully completed!', { component: 'Router' });
@ -382,7 +429,10 @@ export async function registerAllListeners() {
pairingId,
messageId: event.data.messageId,
};
secureLogger.info('📤 Sending PAIRING_CREATED message to UI:', { component: 'Router', data: successMsg });
secureLogger.info('📤 Sending PAIRING_CREATED message to UI:', {
component: 'Router',
data: successMsg,
});
window.parent.postMessage(successMsg, event.origin);
} catch (e) {
const errorMsg = `❌ Failed to create pairing process: ${e}`;
@ -591,7 +641,9 @@ export async function registerAllListeners() {
};
const handleGetPairingId = async (event: MessageEvent) => {
if (event.data.type !== MessageType.GET_PAIRING_ID) {return;}
if (event.data.type !== MessageType.GET_PAIRING_ID) {
return;
}
if (!services.isPaired()) {
const errorMsg = 'Device not paired';
@ -625,7 +677,9 @@ export async function registerAllListeners() {
};
const handleCreateProcess = async (event: MessageEvent) => {
if (event.data.type !== MessageType.CREATE_PROCESS) {return;}
if (event.data.type !== MessageType.CREATE_PROCESS) {
return;
}
if (!services.isPaired()) {
const errorMsg = 'Device not paired';
@ -674,7 +728,9 @@ export async function registerAllListeners() {
};
const handleNotifyUpdate = async (event: MessageEvent) => {
if (event.data.type !== MessageType.NOTIFY_UPDATE) {return;}
if (event.data.type !== MessageType.NOTIFY_UPDATE) {
return;
}
if (!services.isPaired()) {
const errorMsg = 'Device not paired';
@ -712,7 +768,9 @@ export async function registerAllListeners() {
};
const handleValidateState = async (event: MessageEvent) => {
if (event.data.type !== MessageType.VALIDATE_STATE) {return;}
if (event.data.type !== MessageType.VALIDATE_STATE) {
return;
}
if (!services.isPaired()) {
const errorMsg = 'Device not paired';
@ -747,7 +805,9 @@ export async function registerAllListeners() {
};
const handleUpdateProcess = async (event: MessageEvent) => {
if (event.data.type !== MessageType.UPDATE_PROCESS) {return;}
if (event.data.type !== MessageType.UPDATE_PROCESS) {
return;
}
if (!services.isPaired()) {
const errorMsg = 'Device not paired';
@ -831,7 +891,9 @@ export async function registerAllListeners() {
}
}
if (privateData[field]) {continue;}
if (privateData[field]) {
continue;
}
// We've get back all the way to the first state without seeing it, it's a new public field
publicData[field] = newData[field];
@ -858,7 +920,9 @@ export async function registerAllListeners() {
};
const handleDecodePublicData = async (event: MessageEvent) => {
if (event.data.type !== MessageType.DECODE_PUBLIC_DATA) {return;}
if (event.data.type !== MessageType.DECODE_PUBLIC_DATA) {
return;
}
if (!services.isPaired()) {
const errorMsg = 'Device not paired';
@ -892,7 +956,9 @@ export async function registerAllListeners() {
};
const handleHashValue = async (event: MessageEvent) => {
if (event.data.type !== MessageType.HASH_VALUE) {return;}
if (event.data.type !== MessageType.HASH_VALUE) {
return;
}
secureLogger.info('handleHashValue', { component: 'Router', data: event.data });
@ -921,7 +987,9 @@ export async function registerAllListeners() {
};
const handleGetMerkleProof = async (event: MessageEvent) => {
if (event.data.type !== MessageType.GET_MERKLE_PROOF) {return;}
if (event.data.type !== MessageType.GET_MERKLE_PROOF) {
return;
}
try {
const { accessToken, processState, attributeName } = event.data;
@ -948,7 +1016,9 @@ export async function registerAllListeners() {
};
const handleValidateMerkleProof = async (event: MessageEvent) => {
if (event.data.type !== MessageType.VALIDATE_MERKLE_PROOF) {return;}
if (event.data.type !== MessageType.VALIDATE_MERKLE_PROOF) {
return;
}
try {
const { accessToken, merkleProof, documentHash } = event.data;
@ -1017,7 +1087,9 @@ export async function registerAllListeners() {
await handleCreateProcess(event);
break;
case MessageType.CREATE_CONVERSATION:
secureLogger.warn('CREATE_CONVERSATION functionality has been removed', { component: 'Router' });
secureLogger.warn('CREATE_CONVERSATION functionality has been removed', {
component: 'Router',
});
break;
case MessageType.NOTIFY_UPDATE:
await handleNotifyUpdate(event);
@ -1119,7 +1191,9 @@ async function handlePairing4WordsJoin(event: MessageEvent) {
async function cleanPage() {
const container = document.querySelector('#containerId');
if (container) {container.innerHTML = '';}
if (container) {
container.innerHTML = '';
}
}
// Essential functions are now handled directly in the application
@ -1148,7 +1222,9 @@ async function cleanPage() {
// Reload the page to restart the application
window.location.reload();
} catch (error) {
secureLogger.error('❌ Erreur lors de la suppression du compte:', error, { component: 'Router' });
secureLogger.error('❌ Erreur lors de la suppression du compte:', error, {
component: 'Router',
});
alert('❌ Erreur lors de la suppression du compte. Veuillez réessayer.');
}
} else {
@ -1161,7 +1237,9 @@ 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 = '';}
if (container) {
container.innerHTML = '';
}
//initChat();
@ -1188,7 +1266,9 @@ async function handleSecurityKeyManagement(): Promise<boolean> {
const currentMode = await securityModeService.getCurrentMode();
if (!currentMode) {
secureLogger.info('🔐 No security mode configured, redirecting to security setup...', { component: 'Router' });
secureLogger.info('🔐 No security mode configured, redirecting to security setup...', {
component: 'Router',
});
window.location.href = '/src/pages/security-setup/security-setup.html';
return false;
}
@ -1202,11 +1282,15 @@ async function handleSecurityKeyManagement(): Promise<boolean> {
const hasCredentials = await secureCredentialsService.hasCredentials();
if (!hasCredentials) {
secureLogger.info('🔐 No security credentials found, redirecting to wallet setup...', { component: 'Router' });
secureLogger.info('🔐 No security credentials found, redirecting to wallet setup...', {
component: 'Router',
});
window.location.href = '/wallet-setup.html';
return false;
} else {
secureLogger.info('🔐 Security credentials found, verifying access...', { component: 'Router' });
secureLogger.info('🔐 Security credentials found, verifying access...', {
component: 'Router',
});
// Vérifier l'accès aux credentials
const credentials = await secureCredentialsService.retrieveCredentials('');
if (!credentials) {
@ -1220,7 +1304,7 @@ async function handleSecurityKeyManagement(): Promise<boolean> {
} catch (error) {
secureLogger.error('❌ Security key management failed:', error, { component: 'Router' });
secureLogger.info('🔐 Redirecting to security setup...', { component: 'Router' });
window.location.href = '/security-setup.html';
window.location.href = '/security-setup.html';
return false;
}
}
@ -1252,10 +1336,15 @@ async function handlePairing(services: any): Promise<void> {
try {
// Vérifier le statut de pairing
const isPaired = services.isPaired();
secureLogger.debug('🔍 Device pairing status:', { component: 'Router', data: isPaired ? 'Paired' : 'Not paired' });
secureLogger.debug('🔍 Device pairing status:', {
component: 'Router',
data: isPaired ? 'Paired' : 'Not paired',
});
if (!isPaired) {
secureLogger.warn('⚠️ Device not paired, user must complete pairing...', { component: 'Router' });
secureLogger.warn('⚠️ Device not paired, user must complete pairing...', {
component: 'Router',
});
// Le pairing sera géré par la page home
return;
} else {
@ -1280,14 +1369,20 @@ async function startProcessListening(services: any): Promise<void> {
secureLogger.info('📊 Restoring processes from database...', { component: 'Router' });
await services.restoreProcessesFromDB();
} catch (error) {
secureLogger.warn('⚠️ Failed to restore processes from database:', { component: 'Router', data: error });
secureLogger.warn('⚠️ Failed to restore processes from database:', {
component: 'Router',
data: error,
});
}
try {
secureLogger.info('🔐 Restoring secrets from database...', { component: 'Router' });
await services.restoreSecretsFromDB();
} catch (error) {
secureLogger.warn('⚠️ Failed to restore secrets from database:', { component: 'Router', data: error });
secureLogger.warn('⚠️ Failed to restore secrets from database:', {
component: 'Router',
data: error,
});
}
secureLogger.info('✅ Process listening started', { component: 'Router' });

View File

@ -1,4 +1,6 @@
/* eslint-env browser, serviceworker */
import { secureLogger } from '../services/secure-logger';
const EMPTY32BYTES = String('').padStart(64, '0');
self.addEventListener('install', event => {
@ -12,7 +14,11 @@ self.addEventListener('activate', event => {
// Event listener for messages from clients
self.addEventListener('message', async event => {
const data = event.data;
console.log(data);
secureLogger.debug('Database worker received message', {
component: 'DatabaseWorker',
messageType: data?.type,
hasPayload: Boolean(data?.payload)
});
if (data.type === 'SCAN') {
try {
@ -20,13 +26,17 @@ self.addEventListener('message', async event => {
if (myProcessesId && myProcessesId.length != 0) {
const toDownload = await scanMissingData(myProcessesId);
if (toDownload.length != 0) {
console.log('Sending TO_DOWNLOAD message');
secureLogger.info('Database worker sending TO_DOWNLOAD message', {
component: 'DatabaseWorker',
count: toDownload.length
});
event.source.postMessage({ type: 'TO_DOWNLOAD', data: toDownload });
}
} else {
event.source.postMessage({ status: 'error', message: 'Empty lists' });
}
} catch (error) {
secureLogger.error('Database worker scan failed', error, { component: 'DatabaseWorker' });
event.source.postMessage({ status: 'error', message: error.message || 'Unknown error' });
}
} else if (data.type === 'ADD_OBJECT') {
@ -44,6 +54,7 @@ self.addEventListener('message', async event => {
event.ports[0].postMessage({ status: 'success', message: '' });
} catch (error) {
secureLogger.error('Database worker add object failed', error, { component: 'DatabaseWorker' });
event.ports[0].postMessage({ status: 'error', message: error.message || 'Unknown error' });
}
} else if (data.type === 'BATCH_WRITING') {
@ -65,7 +76,10 @@ self.addEventListener('message', async event => {
});
async function scanMissingData(processesToScan) {
console.log('Scanning for missing data...');
secureLogger.debug('Scanning for missing data', {
component: 'DatabaseWorker',
processes: processesToScan?.length ?? 0
});
const myProcesses = await getProcesses(processesToScan);
let toDownload = new Set();
@ -90,7 +104,10 @@ async function scanMissingData(processesToScan) {
} else {
// We remove it if we have it in the set
if (toDownload.delete(hash)) {
console.log(`Removing ${hash} from the set`);
secureLogger.debug('Hash removed from download set', {
component: 'DatabaseWorker',
hashSuffix: hash.slice(-8)
});
}
}
}
@ -98,19 +115,81 @@ async function scanMissingData(processesToScan) {
}
}
console.log(toDownload);
secureLogger.info('Scan complete', {
component: 'DatabaseWorker',
totalMissing: toDownload.size
});
return Array.from(toDownload);
}
const DATABASE_CONFIG = {
name: '4nk',
version: 3
version: 5,
stores: [
{
name: 'wallet',
options: { keyPath: 'pre_id' },
indices: [],
},
{
name: 'credentials',
options: {},
indices: [],
},
{
name: 'pbkdf2keys',
options: {},
indices: [],
},
{
name: 'env',
options: { keyPath: 'key' },
indices: [],
},
{
name: 'labels',
options: { keyPath: 'emoji' },
indices: [],
},
{
name: 'processes',
options: {},
indices: [],
},
{
name: 'shared_secrets',
options: {},
indices: [],
},
{
name: 'unconfirmed_secrets',
options: { autoIncrement: true },
indices: [],
},
{
name: 'diffs',
options: { keyPath: 'value_commitment' },
indices: [
{ name: 'byStateId', keyPath: 'state_id', options: { unique: false } },
{ name: 'byNeedValidation', keyPath: 'need_validation', options: { unique: false } },
{ name: 'byStatus', keyPath: 'validation_status', options: { unique: false } },
],
},
{
name: 'data',
options: {},
indices: [],
},
],
};
async function openDatabase() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DATABASE_CONFIG.name, DATABASE_CONFIG.version);
request.onerror = () => {
secureLogger.error('Database worker failed to open database', request.error, {
component: 'DatabaseWorker'
});
reject(request.error);
};
request.onsuccess = () => {
@ -118,15 +197,26 @@ async function openDatabase() {
};
request.onupgradeneeded = event => {
const db = event.target.result;
if (!db.objectStoreNames.contains('wallet')) {
db.createObjectStore('wallet', { keyPath: 'pre_id' });
}
if (!db.objectStoreNames.contains('credentials')) {
db.createObjectStore('credentials');
}
if (!db.objectStoreNames.contains('pbkdf2keys')) {
db.createObjectStore('pbkdf2keys');
}
secureLogger.info('Database worker upgrading database schema', {
component: 'DatabaseWorker',
version: DATABASE_CONFIG.version
});
DATABASE_CONFIG.stores.forEach(storeConfig => {
if (!db.objectStoreNames.contains(storeConfig.name)) {
const store = db.createObjectStore(storeConfig.name, storeConfig.options);
storeConfig.indices.forEach(indexConfig => {
store.createIndex(indexConfig.name, indexConfig.keyPath, indexConfig.options);
});
} else {
secureLogger.debug('Database store already exists', {
component: 'DatabaseWorker',
store: storeConfig.name
});
}
});
};
});
}
@ -148,6 +238,9 @@ async function getAllProcesses() {
};
request.onerror = () => {
secureLogger.error('Database worker failed to read all processes', request.error, {
component: 'DatabaseWorker'
});
reject(request.error);
};
});
@ -171,7 +264,10 @@ async function getProcesses(processIds) {
const request = store.get(processId);
request.onsuccess = () => resolve(request.result);
request.onerror = () => {
console.error(`Error fetching process ${processId}:`, request.error);
secureLogger.error('Error fetching process', request.error, {
component: 'DatabaseWorker',
processId
});
resolve(undefined);
};
});

View File

@ -253,7 +253,7 @@ export class WebAuthnService {
* Sauvegarde la clé PBKDF2 chiffrée dans IndexedDB
* NE PAS stocker credentialId avec la clé chiffrée
*/
private async savePBKDF2Key(encryptedKey: string, credentialId: string, securityMode: SecurityMode): Promise<void> {
private async savePBKDF2Key(encryptedKey: string, _credentialId: string, securityMode: SecurityMode): Promise<void> {
try {
const db = await this.openDatabase();
secureLogger.debug(`Available stores in ${DATABASE_CONFIG.name}`, { component: 'WebAuthn', stores: Array.from(db.objectStoreNames) });
@ -319,38 +319,37 @@ export class WebAuthnService {
});
if (!result || typeof result !== 'string') {
console.log(`🔍 No PBKDF2 key found for security mode: ${securityMode}`);
secureLogger.debug(`No PBKDF2 key found for security mode: ${securityMode}`, { component: 'WebAuthn' });
return null;
}
// Récupérer le credentialId dynamiquement via WebAuthn
// IMPORTANT: Cela nécessite une interaction utilisateur (authentification biométrique)
console.log('🔐 Requesting WebAuthn authentication to retrieve credential...');
secureLogger.debug('Requesting WebAuthn authentication to retrieve credential', { component: 'WebAuthn' });
// TEST: Try to get credentialId from sessionStorage first
const storedCredentialId = sessionStorage.getItem('webauthn_credential_id');
let credentialId: string | null = null;
if (storedCredentialId) {
console.log('🔐 Using credentialId from sessionStorage:', storedCredentialId);
secureLogger.debug('Using credentialId from sessionStorage', { component: 'WebAuthn' });
credentialId = storedCredentialId;
} else {
// Fallback to WebAuthn
credentialId = await this.getCurrentCredentialId();
if (credentialId) {
console.log('🔐 Storing credentialId in sessionStorage for testing');
secureLogger.debug('Storing credentialId in sessionStorage for testing', { component: 'WebAuthn' });
sessionStorage.setItem('webauthn_credential_id', credentialId);
}
}
if (!credentialId) {
console.log('🔍 WebAuthn authentication required but not available');
console.log(' For proton-pass or os mode, user interaction is required to decrypt the key');
secureLogger.debug('WebAuthn authentication required but not available', { component: 'WebAuthn' });
return null;
}
// Déchiffrer la clé avec le credentialId WebAuthn
console.log('🔐 Decrypting PBKDF2 key with credentialId:', credentialId);
secureLogger.debug('Decrypting PBKDF2 key with credentialId', { component: 'WebAuthn' });
const encrypted = atob(result);
const combined = new Uint8Array(encrypted.length);
for (let i = 0; i < encrypted.length; i++) {
@ -362,7 +361,8 @@ export class WebAuthnService {
const iv = combined.slice(16, 28);
const encryptedData = combined.slice(28);
console.log('🔐 Extraction complete:', {
secureLogger.debug('Extraction complete', {
component: 'WebAuthn',
saltLength: salt.length,
ivLength: iv.length,
encryptedDataLength: encryptedData.length,
@ -398,7 +398,7 @@ export class WebAuthnService {
);
// Déchiffrer
console.log('🔐 Attempting AES-GCM decryption...');
secureLogger.debug('Attempting AES-GCM decryption', { component: 'WebAuthn' });
try {
const decrypted = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: iv },
@ -407,16 +407,16 @@ export class WebAuthnService {
);
const decryptedKey = new TextDecoder().decode(decrypted);
console.log('🔐 PBKDF2 key decrypted with WebAuthn successfully');
secureLogger.debug('PBKDF2 key decrypted with WebAuthn successfully', { component: 'WebAuthn' });
return decryptedKey;
} catch (decryptError) {
console.error('❌ Decryption failed:', decryptError);
console.error('❌ Decryption error details:', {
secureLogger.error('Decryption failed', decryptError as Error, { component: 'WebAuthn' });
secureLogger.error('Decryption error details', decryptError as Error, {
component: 'WebAuthn',
errorName: decryptError instanceof Error ? decryptError.name : 'Unknown',
errorMessage: decryptError instanceof Error ? decryptError.message : String(decryptError),
credentialId: credentialId,
iv: Array.from(iv),
salt: Array.from(salt)
ivLength: iv.length,
saltLength: salt.length
});
throw decryptError;
}
@ -448,7 +448,7 @@ export class WebAuthnService {
});
if (credential && credential.id) {
console.log('🔐 WebAuthn credential ID retrieved:', credential.id);
secureLogger.debug('WebAuthn credential ID retrieved', { component: 'WebAuthn' });
return credential.id;
}
@ -456,8 +456,7 @@ export class WebAuthnService {
} catch (error) {
// Si erreur de permission ou timeout, c'est normal
// L'utilisateur n'a peut-être pas interagi
console.log('🔍 WebAuthn credential retrieval failed:', error);
console.log(' User interaction may be required for authentication');
secureLogger.debug('WebAuthn credential retrieval failed', { component: 'WebAuthn' });
return null;
}
}
@ -483,12 +482,12 @@ export class WebAuthnService {
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
console.log(`🔄 ${DATABASE_CONFIG.name} database upgrade needed, creating stores...`);
secureLogger.debug(`${DATABASE_CONFIG.name} database upgrade needed, creating stores...`, { component: 'WebAuthn' });
if (!db.objectStoreNames.contains(DATABASE_CONFIG.stores.pbkdf2keys.name)) {
db.createObjectStore(DATABASE_CONFIG.stores.pbkdf2keys.name);
console.log(`${DATABASE_CONFIG.stores.pbkdf2keys.name} store created`);
secureLogger.debug(`${DATABASE_CONFIG.stores.pbkdf2keys.name} store created`, { component: 'WebAuthn' });
} else {
console.log(`${DATABASE_CONFIG.stores.pbkdf2keys.name} store already exists`);
secureLogger.debug(`${DATABASE_CONFIG.stores.pbkdf2keys.name} store already exists`, { component: 'WebAuthn' });
}
};
});

View File

@ -2,6 +2,49 @@ import Services from './service';
import { DATABASE_CONFIG } from './database-config';
import { secureLogger } from './secure-logger';
type IndexedDBKeyPath = string | string[];
type StoreDefinition = {
name: string;
options: IDBObjectStoreParameters;
indices: Array<{
name: string;
keyPath: IndexedDBKeyPath;
options: IDBIndexParameters;
}>;
};
const buildStoreDefinitions = (): Record<string, StoreDefinition> => {
return Object.values(DATABASE_CONFIG.stores).reduce<Record<string, StoreDefinition>>(
(definitions, storeConfig) => {
const options: IDBObjectStoreParameters = {};
if (storeConfig.keyPath !== null && storeConfig.keyPath !== undefined) {
options.keyPath = storeConfig.keyPath as IndexedDBKeyPath;
}
if ('autoIncrement' in storeConfig && storeConfig.autoIncrement) {
options.autoIncrement = true;
}
const indices = Array.from(storeConfig.indices ?? []).map(indexConfig => ({
name: indexConfig.name,
keyPath: indexConfig.keyPath as IndexedDBKeyPath,
options: { unique: indexConfig.unique ?? false },
}));
definitions[storeConfig.name] = {
name: storeConfig.name,
options,
indices,
};
return definitions;
},
{}
);
};
export class Database {
private static instance: Database;
private db: IDBDatabase | null = null;
@ -11,52 +54,7 @@ export class Database {
private messageChannel: MessageChannel | null = null;
private messageChannelForGet: MessageChannel | null = null;
private serviceWorkerCheckIntervalId: number | null = null;
private storeDefinitions = {
AnkLabels: {
name: 'labels',
options: { keyPath: 'emoji' },
indices: [],
},
AnkWallet: {
name: 'wallet',
options: { keyPath: 'pre_id' },
indices: [],
},
AnkProcess: {
name: 'processes',
options: {},
indices: [],
},
AnkSharedSecrets: {
name: 'shared_secrets',
options: {},
indices: [],
},
AnkUnconfirmedSecrets: {
name: 'unconfirmed_secrets',
options: { autoIncrement: true },
indices: [],
},
AnkPendingDiffs: {
name: 'diffs',
options: { keyPath: 'value_commitment' },
indices: [
{ name: 'byStateId', keyPath: 'state_id', options: { unique: false } },
{ name: 'byNeedValidation', keyPath: 'need_validation', options: { unique: false } },
{ name: 'byStatus', keyPath: 'validation_status', options: { unique: false } },
],
},
AnkData: {
name: 'data',
options: {},
indices: [],
},
AnkPBKDF2Keys: {
name: 'pbkdf2keys',
options: {},
indices: [],
},
};
private storeDefinitions: Record<string, StoreDefinition> = buildStoreDefinitions();
// Private constructor to prevent direct instantiation from outside
private constructor() {}

View File

@ -132,14 +132,21 @@ export class DeviceReaderService {
// L'adresse est stockée dans device.sp_wallet.address
const address = device.sp_wallet?.address;
if (address) {
console.log('✅ DeviceReaderService: Device address retrieved:', address);
secureLogger.info('DeviceReaderService: Device address retrieved', {
component: 'DeviceReader',
addressSuffix: address.slice(-6)
});
return address;
}
console.warn('⚠️ DeviceReaderService: Device found but no address in sp_wallet.address');
secureLogger.warn('DeviceReaderService: Device found but no address in sp_wallet.address', {
component: 'DeviceReader'
});
return null;
} catch (error) {
console.error('❌ DeviceReaderService: Error getting device address:', error);
secureLogger.error('DeviceReaderService: Error getting device address', error as Error, {
component: 'DeviceReader'
});
throw error;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -23,7 +23,7 @@ export async function checkPBKDF2Key(): Promise<{ key: string; mode: SecurityMod
const hasKey = await secureCredentialsService.hasPBKDF2Key(mode);
if (hasKey) {
const key = await secureCredentialsService.retrievePBKDF2Key(mode);
if (key) {
if (key && key.trim().length > 0) {
secureLogger.info(`PBKDF2 key found in pbkdf2keys store for security mode: ${mode}`, { component: 'PrerequisitesUtils' });
return { key, mode };
}

View File

@ -3,6 +3,8 @@
* Traite les données lourdes sans bloquer le thread principal
*/
import { secureLogger } from '../services/secure-logger';
export interface EncoderMessage {
type: 'encode' | 'decode';
data: any;
@ -115,11 +117,13 @@ async function decodeData(data: any): Promise<any> {
// Gérer les erreurs non capturées
self.addEventListener('error', (error) => {
// Note: secureLogger not available in worker context
console.error('Encoder worker error:', error);
secureLogger.error('Encoder worker error', error instanceof ErrorEvent ? error.error : error, {
component: 'EncoderWorker'
});
});
self.addEventListener('unhandledrejection', (event) => {
// Note: secureLogger not available in worker context
console.error('Encoder worker unhandled rejection:', event.reason);
secureLogger.error('Encoder worker unhandled rejection', event.reason, {
component: 'EncoderWorker'
});
});