diff --git a/CLAUDE.md b/CLAUDE.md index f40c809..b26fa5d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -454,6 +454,53 @@ hotkeys autofill, etc. **Device-only** (localStorage seulement) : `quickUnlockEnabled` (DPAPI lié au compte Windows), `autofillEnabled` (toggle hotkey Win32), `rememberedUsername` (auth screen autofill local). +## Sync (WebDAV, auto-merge) + +Multi-device sync via a user-hosted WebDAV server (Nextcloud, ownCloud, +Apache mod_dav). Auto-merge strategy: last-write-wins per entry on +`updated_at`, tombstones propagate hard-deletes. No conflict UI — solo +personal use rarely produces simultaneous edits. + +Foundations : +- `vault_entries.uuid` (TEXT, indexed) — stable cross-device identity. + Migration backfills existing rows via `hex(randomblob)` → RFC 4122 v4. +- `entry_tombstones (user_id, uuid, deleted_at)` — UNIQUE(user_id, uuid), + written on hard-delete (`DELETE permanent=1`, trash empty, auto-purge). +- GET `/entries` returns uuid ; POST/bulk-import accept it (mint fresh + if absent) ; PUT keeps it immutable. +- GET `/entries/tombstones` lists local tombstones. +- POST `/entries/tombstones {uuids:[...]}` adds tombstones + hard-deletes + any local rows matching those uuids (idempotent via INSERT OR IGNORE). + +Transport ([UMainForm.pas](delphi-backend/UMainForm.pas)) : +- `cmd://webdav/get|put|test?reqId=&url=&user=&pwd=[&data=]` → async via + `THTTPClient` (WinHTTP under the hood, no OpenSSL DLLs required). + Basic auth, 10s connect / 30s response timeout. Callback + `Bridge.onWebdavResult(reqId, status, payload)`. + +Settings : all config in DPAPI prefs (`syncEnabled`, `syncUrl`, +`syncUser`, `syncPwd`, `syncEncPwd`, `syncPreBackup`, `syncLast`). +**`syncEncPwd` MUST be the same on every device** — it's the secret +that encrypts the WebDAV-stored snapshot. User sets it once per +device, never transmitted. + +`runSyncNow()` flow : +1. (Optional) Write `vault-presync-yyyymmdd-HHMMSS.json` to the + auto-backup folder if enabled. +2. `webdav/get` → 404 = first sync, treat as empty remote. +3. Decrypt with `syncEncPwd` (reuses `encryptExportPayload` container). +4. POST remote tombstones → server hard-deletes local matches. +5. Folders : add missing ones additively (don't touch existing). +6. Entries : for each remote uuid → not in local = POST keeping uuid + + restore attachments ; both sides have it = compare `updated_at`, + PUT if remote newer. +7. `loadEntries()` + `buildSyncSnapshot()` for the post-merge state. +8. `webdav/put` push the merged snapshot. +9. Toast `X added · Y updated · Z deleted`. + +Sensitive actions (export, change master pw, recovery code…) still +require master pw via `askReauth` — sync never substitutes. + ## PIN unlock Optional shortcut unlock with a 4–12 digit PIN, complementary to Quick diff --git a/TEST_SYNC.md b/TEST_SYNC.md new file mode 100644 index 0000000..10ced6d --- /dev/null +++ b/TEST_SYNC.md @@ -0,0 +1,135 @@ +# Test plan — WebDAV sync (auto-merge) + +Server : `wsgidav --host=127.0.0.1 --port=8080 --root=E:\webdav-test --auth=anonymous` +URL Settings : `http://127.0.0.1:8080/vault-sync.json` +User/pwd Settings : vides (anonymous) +Sync password : choisir une fois, **identique sur les 2 devices** + +--- + +## 0. Setup deux devices RÉELLEMENT séparés + +Le sync est par-vault. Un même `vault.db` avec 2 comptes user ≠ 2 devices. + +- [ ] **Device A** : exe actuel `Z:\password-manager\delphi-backend\Win32\Debug\PMServer.exe` +- [ ] **Device B** : + - Copier **uniquement le `.exe`** dans `D:\PMServer-B\` (assets.res est déjà embarqué dedans) + - Lancer → crée un user `userB` avec un nouveau master pw + - `vault.db` de B est créé à côté de l'exe B (séparé de A) +- [ ] Vérifier les 2 lancent sur des ports différents (chacun écrit son port au boot dans le log) + +## 1. Connexion server + +- [ ] wsgidav tourne (logs visibles, "Serving on http://127.0.0.1:8080") +- [ ] A : Settings → Sync → URL + Set sync password (`testsync`) → Test connection → toast `Connection OK · snapshot not created yet` +- [ ] B : idem mais **même sync password** `testsync` → Test connection → toast OK aussi + +## 2. Premier push (A vide → server) + +- [ ] A : créer 3 entries distinctes (`gmail`, `bank`, `github` par ex.) + 1 note + 1 folder custom `Work` +- [ ] A : **Sync now** → wsgidav log `GET 404` + `PUT 201` → toast `Sync complete — 0 added · 0 updated · 0 deleted` +- [ ] Vérifier `Get-ChildItem E:\webdav-test` → `vault-sync.json` existe (~quelques KB) + +## 3. Premier pull (B vide ← server) + +- [ ] B : **Sync now** → wsgidav log `GET 200` + `PUT 201` → toast `Sync complete — 5 added · 0 updated · 0 deleted` (3 logins + note + ??? folder ne compte pas dans `added`) +- [ ] B : vérifier que les 3 entries + la note sont visibles dans la grille +- [ ] B : ouvrir `gmail` → password déchiffrable +- [ ] B : ouvrir la note → texte lisible +- [ ] B : sidebar Folders → `Work` présent avec sa couleur+icône + +## 4. Auto-merge ajout des deux côtés + +- [ ] A : créer entry `slack` +- [ ] B : créer entry `discord` +- [ ] A : Sync now → toast `1 added` (récupère `discord`) +- [ ] B : Sync now → toast `1 added` (récupère `slack`) +- [ ] Les deux devices ont maintenant 5 + 2 = 7 entries + +## 5. Last-write-wins + +- [ ] A : éditer `gmail` → changer username en `user-from-A` → Save +- [ ] B (sans sync entre temps) : éditer `gmail` → changer username en `user-from-B` → Save (B a `updated_at` plus récent) +- [ ] A : Sync now → toast `0 added · 1 updated · 0 deleted` → `gmail.username` devient `user-from-B` +- [ ] Inverse pour confirmer : édit A puis édit B puis sync B en premier → B garde sa version (rien à update côté B), puis sync A → A bascule sur B + +## 6. Tombstones (delete propagation) + +- [ ] A : delete `slack` (soft) → Trash → Empty trash (hard-delete = tombstone créé) +- [ ] A : Sync now → push tombstone +- [ ] B : Sync now → toast inclut `1 deleted` → `slack` disparait côté B +- [ ] Recréer `slack` côté B → Sync now → vérifier qu'il ne ressuscite **pas** côté A (tombstone réutilisé sauf si nouveau uuid mint → vérifier ce comportement) + +## 7. Custom fields + TOTP préservés + +- [ ] A : créer entry `aws` avec TOTP secret valide + 2 custom fields (`access_key`, `secret_key` is_secret=true) +- [ ] A : Sync now +- [ ] B : Sync now → `aws` apparaît +- [ ] B : ouvrir `aws` → TOTP code visible et tick · les 2 custom fields visibles · `secret_key` masqué (is_secret) +- [ ] B : éditer un custom field → Save → Sync now +- [ ] A : Sync now → modif reflétée + +## 8. Attachments round-trip + +- [ ] A : ouvrir une entry → Attach file → upload PDF < 1 MB +- [ ] A : Sync now (wsgidav log → file size augmente sensiblement) +- [ ] B : Sync now → ouvrir la même entry → attachment visible → Download → fichier décrypté identique + +## 9. Pre-sync backup + +- [ ] A : Settings → cocher "Create a local backup before each sync" +- [ ] A : Sync now → `Get-ChildItem "C:\Users\zakar\Desktop\backup test\vault-presync-*.json"` → fichier daté du jour existe +- [ ] Tester restore : Import vault → choisir le `.json` → tape `testsync` → entries restaurées + +## 10. Auth WebDAV (optionnel) + +Si tu veux tester avec un vrai user/pwd (au lieu d'anonymous) : +``` +wsgidav --host=127.0.0.1 --port=8080 --root=E:\webdav-test ^ + --auth=basic --user-mapping={"/":{"alice":{"password":"s3cret","roles":["editor"]}}} +``` +- [ ] A : Username `alice` + Password `s3cret` → Test connection OK +- [ ] A : vider user/pwd → Test connection → toast `Auth failed (401)` + +## 11. Erreurs réseau + +- [ ] Tuer wsgidav (Ctrl+C dans son terminal) +- [ ] A : Test connection → toast `Network error: ...` +- [ ] A : Sync now → toast `Sync pull failed: ...` (pas d'écrasement local) +- [ ] Relancer wsgidav → re-Sync now → reprend normalement + +## 12. Conflict — édit + delete sur le même entry + +- [ ] A : delete `github` → hard-delete (Empty trash) → Sync now (push tombstone) +- [ ] B (sans sync entre) : édite `github` (la version locale a un `updated_at` plus récent que la deletion) +- [ ] B : Sync now → comportement attendu = entry deletée (tombstones gagnent toujours sur update — vérifier que c'est bien ça) + +## 13. Vault locked pendant sync + +- [ ] A : Lock vault +- [ ] A : (pas accès Settings — locked) — vérifier qu'il n'y a pas d'auto-sync silencieux qui tenterait quand même +- [ ] Unlock → Sync now → fonctionne + +## 14. Master pw rotation + sync + +- [ ] A : change master password → re-encrypte toutes les entries localement avec nouvelle clé +- [ ] A : Sync now → push avec **même** sync password (encPwd indépendant du master) → toast OK +- [ ] B : Sync now → toast `0 added · 0 updated · 0 deleted` (les uuids n'ont pas changé, les `updated_at` non plus pour la plupart) + +--- + +## Critères de réussite + +- ✅ Pull récupère systématiquement les entries manquantes (added > 0 quand attendu) +- ✅ Push ne supprime **jamais** silencieusement de données (sauf via tombstone explicite) +- ✅ Pre-sync backup créé si dossier configuré (sinon skip silencieux, OK) +- ✅ Erreur réseau ou auth → toast clair, **pas** d'écrasement +- ✅ Sync password divergent → toast `Remote decrypt failed — wrong sync password?` + pas de push +- ✅ Tombstones propagent les deletes hard + +## Gotchas connus + +- **Tester avec 2 vraies instances séparées**, pas 2 users dans la même DB +- Sync password ≠ master password ; doit être identique sur tous les devices +- Pre-sync backup réutilise le dossier auto-backup (pas de dossier dédié actuellement) +- Le snapshot WebDAV contient TOUTES les entries en plaintext sous le sync password — ne pas confondre avec la sécurité par master (qui reste pour les blobs DB locaux) diff --git a/css/style.css b/css/style.css index 859a91e..0c4c009 100644 --- a/css/style.css +++ b/css/style.css @@ -2059,10 +2059,20 @@ body[data-editor-position="center"] #settingsPanel.is-open { opacity: 1; pointer-events: auto; } -/* No dim/blur in center mode — the panel doesn't actually block - interaction (cards, sidebar, topbar stay clickable without - dismissing it), so painting a modal-style backdrop would lie about - the behaviour. The panel just floats above the page. */ +/* Center mode = true modal: dim + blur backdrop, click anywhere + outside the panel dismisses it (handled in JS). The backdrop is + painted via a body pseudo-element so it covers everything but + the active panel. */ +body[data-editor-position="center"]:has(#slideover.is-open)::before, +body[data-editor-position="center"]:has(#settingsPanel.is-open)::before { + content: ''; + position: fixed; inset: 0; + background: rgba(0, 0, 0, 0.45); + backdrop-filter: blur(4px); + -webkit-backdrop-filter: blur(4px); + z-index: 45; /* above topbar (40), below .slideover (50) */ + pointer-events: auto; /* swallow clicks so cards/sidebar don't see them */ +} .slideover-header { display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; diff --git a/delphi-backend/Handlers/PM.Handler.Entries.pas b/delphi-backend/Handlers/PM.Handler.Entries.pas index 95433d4..6f11f44 100644 --- a/delphi-backend/Handlers/PM.Handler.Entries.pas +++ b/delphi-backend/Handlers/PM.Handler.Entries.pas @@ -28,6 +28,21 @@ begin if Result = '' then Result := ADefault; end; +// RFC 4122 v4 UUID — lowercase canonical hex with dashes, no braces. +// Used as the cross-device stable identity for vault_entries. +function NewUUIDv4: string; +var + G: TGUID; + S: string; +begin + CreateGUID(G); + S := GUIDToString(G); + // Strip surrounding braces RTL adds, lowercase the rest. + if (Length(S) > 0) and (S[1] = '{') then + S := Copy(S, 2, Length(S) - 2); + Result := LowerCase(S); +end; + // SQLite DATETIME columns: FireDAC parses to TDateTime internally, then AsString // would format in system locale (DD/MM/YYYY in French). Force ISO format // 'yyyy-mm-dd hh:nn:ss' which is what api.php / SQLite text storage uses and @@ -132,6 +147,8 @@ begin LObj.AddPair('template', TJSONNull.Create) else LObj.AddPair('template', LQ.FieldByName('template').AsString); + // Stable cross-device identity (always populated post-migration). + LObj.AddPair('uuid', LQ.FieldByName('uuid').AsString); // Custom fields: opaque ciphertext + IV, treated identically to // password / totp_secret. NULL → JSON null so the client can // distinguish "never set" from "empty array stored". @@ -165,6 +182,117 @@ begin TJSONHelper.SendJSON(AResponse, LArr); end; +// ===== GET /entries/tombstones ============================================== +// Sync helper — returns the uuid + deleted_at of every permanently-removed +// entry so the merge engine can propagate deletes to other devices. + +procedure HandleGetTombstones(ARequest: TIdHTTPRequestInfo; + AResponse: TIdHTTPResponseInfo; const AParams: TArray); +var + LUserId: Integer; + LQ: TFDQuery; + LArr: TJSONArray; + LObj: TJSONObject; +begin + try + LUserId := Authenticate(ARequest, AResponse); + except + on ESessionRejected do Exit; + end; + + LArr := TJSONArray.Create; + DB.Lock; + try + LQ := TFDQuery.Create(nil); + try + LQ.Connection := DB.Connection; + LQ.SQL.Text := + 'SELECT uuid, deleted_at FROM entry_tombstones ' + + 'WHERE user_id = :uid ORDER BY deleted_at DESC'; + LQ.ParamByName('uid').AsInteger := LUserId; + LQ.Open; + while not LQ.Eof do + begin + LObj := TJSONObject.Create; + LObj.AddPair('uuid', LQ.FieldByName('uuid').AsString); + LObj.AddPair('deleted_at', ISODateTimeField(LQ.FieldByName('deleted_at'))); + LArr.Add(LObj); + LQ.Next; + end; + finally + LQ.Free; + end; + finally + DB.Unlock; + end; + TJSONHelper.SendJSON(AResponse, LArr); +end; + +// ===== POST /entries/tombstones ============================================= +// Sync helper — body {uuids: ["x","y", ...]} adds tombstones for entries +// deleted on another device. Idempotent (UNIQUE constraint). + +procedure HandlePostTombstones(ARequest: TIdHTTPRequestInfo; + AResponse: TIdHTTPResponseInfo; const AParams: TArray); +var + LUserId, I, LAdded: Integer; + LBody: TJSONObject; + LArr: TJSONArray; + LQ: TFDQuery; + LUuid: string; +begin + try + LUserId := Authenticate(ARequest, AResponse); + RequireCSRF(ARequest, AResponse, LUserId); + except + on ESessionRejected do Exit; + end; + + LBody := TJSONHelper.ReadBody(ARequest); + LAdded := 0; + try + LArr := LBody.GetValue('uuids'); + if (LArr = nil) or (LArr.Count = 0) then + begin + TJSONHelper.SendOK(AResponse, 'No tombstones'); + Exit; + end; + DB.Lock; + try + LQ := TFDQuery.Create(nil); + try + LQ.Connection := DB.Connection; + LQ.SQL.Text := + 'INSERT OR IGNORE INTO entry_tombstones (user_id, uuid) ' + + 'VALUES (:uid, :u)'; + for I := 0 to LArr.Count - 1 do + begin + LUuid := Trim(LArr.Items[I].Value); + if LUuid = '' then Continue; + LQ.ParamByName('uid').AsInteger := LUserId; + LQ.ParamByName('u').AsString := LUuid; + LQ.ExecSQL; + if LQ.RowsAffected > 0 then Inc(LAdded); + end; + // Hard-delete any local entries whose UUID just received a + // tombstone — propagates remote deletes during sync pull. + LQ.SQL.Text := + 'DELETE FROM vault_entries WHERE user_id = :uid AND uuid IN ' + + ' (SELECT uuid FROM entry_tombstones WHERE user_id = :uid)'; + LQ.ParamByName('uid').AsInteger := LUserId; + LQ.ExecSQL; + finally + LQ.Free; + end; + finally + DB.Unlock; + end; + finally + LBody.Free; + end; + TJSONHelper.SendOK(AResponse, IntToStr(LAdded) + ' tombstones added'); +end; + // ===== POST /entries ========================================================= procedure HandleCreateEntry(ARequest: TIdHTTPRequestInfo; @@ -173,7 +301,7 @@ var LUserId, LNewId: Integer; LBody, LObj: TJSONObject; LSite, LTitle, LUser, LFolder, LEnc, LIV, LTags, LNow, LTotpSec, LTotpIv, - LKind, LCf, LCfIv, LIcon, LTemplate: string; + LKind, LCf, LCfIv, LIcon, LTemplate, LUuid: string; LQ: TFDQuery; begin try @@ -200,6 +328,10 @@ begin LCfIv := LBody.GetValue('custom_fields_iv', ''); LIcon := LBody.GetValue('icon_b64', ''); LTemplate:= Trim(LBody.GetValue('template', '')); + // Caller may bring its own UUID (sync restore / import preserving + // identity). Otherwise the server mints a fresh one. + LUuid := Trim(LBody.GetValue('uuid', '')); + if LUuid = '' then LUuid := NewUUIDv4; finally LBody.Free; end; @@ -229,9 +361,9 @@ begin 'INSERT INTO vault_entries ' + '(user_id, site, title, username, encrypted_password, iv, encryption_method, ' + ' folder, tags, totp_secret, totp_iv, kind, custom_fields, custom_fields_iv,' + - ' icon_b64, template, created_at, updated_at, password_changed_at) ' + + ' icon_b64, template, uuid, created_at, updated_at, password_changed_at) ' + 'VALUES (:uid, :s, :tt, :u, :e, :i, ''client'', :f, :t, :ts, :tiv, :k, ' + - ' :cf, :cfiv, :ic, :tpl, :c, :c2, :c)'; + ' :cf, :cfiv, :ic, :tpl, :uuid, :c, :c2, :c)'; LQ.ParamByName('uid').AsInteger := LUserId; LQ.ParamByName('s').AsString := LSite; LQ.ParamByName('tt').AsString := LTitle; @@ -266,6 +398,7 @@ begin LQ.ParamByName('tpl').DataType := ftString; if LTemplate = '' then LQ.ParamByName('tpl').Clear else LQ.ParamByName('tpl').AsString := LTemplate; + LQ.ParamByName('uuid').AsString := LUuid; LQ.ParamByName('c').AsString := LNow; LQ.ParamByName('c2').AsString := LNow; LQ.ExecSQL; @@ -280,6 +413,7 @@ begin LogAudit(LUserId, 'add_entry', GetClientIP(ARequest)); LObj := TJSONObject.Create; LObj.AddPair('id', TJSONNumber.Create(LNewId)); + LObj.AddPair('uuid', LUuid); LObj.AddPair('site', LSite); LObj.AddPair('title', LTitle); LObj.AddPair('username', LUser); @@ -475,7 +609,19 @@ begin try LQ.Connection := DB.Connection; if LPermanent then - LQ.SQL.Text := 'DELETE FROM vault_entries WHERE id=:id AND user_id=:uid' + begin + // Record a tombstone BEFORE the delete so the sync engine can + // propagate this removal to other devices. UPSERT semantics — + // re-deleting an already-tombstoned uuid is a no-op. + LQ.SQL.Text := + 'INSERT OR IGNORE INTO entry_tombstones (user_id, uuid) ' + + 'SELECT user_id, uuid FROM vault_entries ' + + 'WHERE id = :id AND user_id = :uid AND uuid IS NOT NULL'; + LQ.ParamByName('id').AsInteger := LId; + LQ.ParamByName('uid').AsInteger := LUserId; + LQ.ExecSQL; + LQ.SQL.Text := 'DELETE FROM vault_entries WHERE id=:id AND user_id=:uid'; + end else LQ.SQL.Text := 'UPDATE vault_entries SET deleted=1, deleted_at=datetime(''now'') ' + @@ -870,6 +1016,16 @@ begin LQ := TFDQuery.Create(nil); try LQ.Connection := DB.Connection; + // Tombstones FIRST so the sync engine can propagate the purge. + LQ.SQL.Text := + 'INSERT OR IGNORE INTO entry_tombstones (user_id, uuid) ' + + 'SELECT user_id, uuid FROM vault_entries ' + + 'WHERE user_id = :uid AND deleted = 1 AND uuid IS NOT NULL ' + + ' AND deleted_at IS NOT NULL ' + + ' AND (julianday(''now'') - julianday(deleted_at)) >= :d'; + LQ.ParamByName('uid').AsInteger := LUserId; + LQ.ParamByName('d').AsInteger := LDays; + LQ.ExecSQL; LQ.SQL.Text := 'DELETE FROM vault_entries ' + 'WHERE user_id = :uid AND deleted = 1 ' + @@ -914,6 +1070,12 @@ begin LQ := TFDQuery.Create(nil); try LQ.Connection := DB.Connection; + LQ.SQL.Text := + 'INSERT OR IGNORE INTO entry_tombstones (user_id, uuid) ' + + 'SELECT user_id, uuid FROM vault_entries ' + + 'WHERE user_id = :uid AND deleted = 1 AND uuid IS NOT NULL'; + LQ.ParamByName('uid').AsInteger := LUserId; + LQ.ExecSQL; LQ.SQL.Text := 'DELETE FROM vault_entries WHERE user_id=:uid AND deleted=1'; LQ.ParamByName('uid').AsInteger := LUserId; LQ.ExecSQL; @@ -940,7 +1102,7 @@ var LBody, LObj, LEntry: TJSONObject; LArr, LIds: TJSONArray; LSite, LTitle, LUser, LFolder, LEnc, LIV, LTags, LTotpSec, LTotpIv, LNow, - LKind, LCf, LCfIv, LIcon, LTemplate: string; + LKind, LCf, LCfIv, LIcon, LTemplate, LUuid: string; LQ: TFDQuery; begin try @@ -985,9 +1147,9 @@ begin 'INSERT INTO vault_entries ' + '(user_id, site, title, username, encrypted_password, iv, encryption_method, ' + ' folder, tags, totp_secret, totp_iv, kind, custom_fields, custom_fields_iv,' + - ' icon_b64, template, created_at, updated_at) ' + + ' icon_b64, template, uuid, created_at, updated_at) ' + 'VALUES (:uid, :s, :tt, :u, :e, :i, ''client'', :f, :t, :ts, :tiv, :k, ' + - ' :cf, :cfiv, :ic, :tpl, :c, :c2)'; + ' :cf, :cfiv, :ic, :tpl, :uuid, :c, :c2)'; // Declare optional param types ONCE — the prepared statement is // reused across every imported entry, and FireDAC needs the // type set before the first .Clear call would otherwise fail @@ -1021,6 +1183,8 @@ begin LCfIv := LEntry.GetValue('custom_fields_iv', ''); LIcon := LEntry.GetValue('icon_b64', ''); LTemplate:= Trim(LEntry.GetValue('template', '')); + LUuid := Trim(LEntry.GetValue('uuid', '')); + if LUuid = '' then LUuid := NewUUIDv4; // Ciphertext is always required. Site is required only for // logins — notes legitimately have no site (their body lives @@ -1055,6 +1219,7 @@ begin if LIcon = '' then LQ.ParamByName('ic').Clear else LQ.ParamByName('ic').Value := LIcon; if LTemplate = '' then LQ.ParamByName('tpl').Clear else LQ.ParamByName('tpl').AsString := LTemplate; + LQ.ParamByName('uuid').AsString := LUuid; LQ.ParamByName('c').AsString := LNow; LQ.ParamByName('c2').AsString := LNow; LQ.ExecSQL; @@ -1136,6 +1301,8 @@ initialization Router.Register('DELETE', '/entries/trash/empty', HandleEmptyTrash); Router.Register('DELETE', '/entries/trash/old', HandleAutoPurgeTrash); Router.Register('DELETE', '/entries/icons/all', HandleClearAllIcons); + Router.Register('GET', '/entries/tombstones', HandleGetTombstones); + Router.Register('POST', '/entries/tombstones', HandlePostTombstones); Router.Register('POST', '/entries/bulk-import', HandleBulkImport); Router.Register('POST', '/entries/(\d+)/restore', HandleRestoreEntry); Router.Register('POST', '/entries/(\d+)/favorite', HandleToggleFavorite); diff --git a/delphi-backend/Source/PM.Bridge.pas b/delphi-backend/Source/PM.Bridge.pas index 6a4d72f..30363ae 100644 --- a/delphi-backend/Source/PM.Bridge.pas +++ b/delphi-backend/Source/PM.Bridge.pas @@ -92,6 +92,12 @@ type FSavedPlacement: TWindowPlacement; FHasSavedPlacement: Boolean; FOnSystemLock: TProc; + // Set TRUE the moment Windows tells us the session is ending + // (WM_QUERYENDSESSION / WM_ENDSESSION). FormCloseQuery checks this + // to bypass the "minimize to tray" intercept so the form closes + // normally and the DB connection is checkpointed instead of being + // force-killed (which leaves -shm / -wal files behind). + FShutdownPending: Boolean; FOnTrayRestore: TProc; FOnLockRequest: TProc; FOnQuit: TProc; @@ -158,6 +164,9 @@ type property AutofillRegistered: Boolean read FAutofillRegistered; // Fired on main thread when Windows locks the session (WTS_SESSION_LOCK). property OnSystemLock: TProc read FOnSystemLock write FOnSystemLock; + // True once WM_QUERYENDSESSION (or WM_ENDSESSION) has been received. + // FormCloseQuery uses this to allow normal close during shutdown. + property ShutdownPending: Boolean read FShutdownPending; // Fired on main thread when the user clicks the tray icon. property OnTrayRestore: TProc read FOnTrayRestore write FOnTrayRestore; // Fired when the user picks "Lock vault" from the tray menu. Handler @@ -735,6 +744,18 @@ begin if Assigned(FOnSystemLock) then FOnSystemLock(); end + else if (AMsg.Msg = WM_QUERYENDSESSION) or (AMsg.Msg = WM_ENDSESSION) then + begin + // Windows is logging off / shutting down / restarting. Flip the flag + // so FormCloseQuery lets the form actually close instead of + // minimizing to tray — otherwise Windows force-kills us after the + // shutdown timeout and SQLite's WAL/SHM never get checkpointed. + // Return TRUE (do not block shutdown). DefWindowProc returns TRUE + // by default for WM_QUERYENDSESSION, so we just don't assign Result. + FShutdownPending := True; + AMsg.Result := 1; + end + else if (AMsg.Msg <> 0) and (AMsg.Msg = WM_PMShowMessage) then begin // A second instance was launched and PostMessage'd HWND_BROADCAST. diff --git a/delphi-backend/Source/PM.Database.pas b/delphi-backend/Source/PM.Database.pas index 0081509..4f78e1d 100644 --- a/delphi-backend/Source/PM.Database.pas +++ b/delphi-backend/Source/PM.Database.pas @@ -314,6 +314,42 @@ begin // Drives the card/table label so notes-with-fields read as "Credit card" // instead of the generic "Encrypted note" placeholder. AddColumnIfMissing('vault_entries', 'template', 'TEXT'); + // Stable identity that survives export/import + cross-device sync. + // SQLite `id` is autoincrement local-only — useless to match the same + // logical entry across two installs. Populate existing rows with a + // fresh UUID v4 below so the migration is non-destructive. + AddColumnIfMissing('vault_entries', 'uuid', 'TEXT'); + FConn.ExecSQL( + 'CREATE INDEX IF NOT EXISTS idx_entries_uuid ' + + ' ON vault_entries(uuid)'); + // Backfill UUIDs for legacy rows that landed before the column existed. + // SQLite has no native uuid() — emit one via hex(randomblob) + manual + // dashes (RFC 4122 v4 = 8-4-4-4-12 hex, version nibble forced to 4, + // variant nibble high bits 10). + FConn.ExecSQL( + 'UPDATE vault_entries SET uuid = ' + + ' lower(hex(randomblob(4))) || ''-'' || ' + + ' lower(hex(randomblob(2))) || ''-4'' || ' + + ' substr(lower(hex(randomblob(2))), 2) || ''-'' || ' + + ' substr(''89ab'', 1 + (abs(random()) % 4), 1) || ' + + ' substr(lower(hex(randomblob(2))), 2) || ''-'' || ' + + ' lower(hex(randomblob(6))) ' + + 'WHERE uuid IS NULL OR uuid = '''''); + // Tombstones: every hard-delete inserts a row here so the sync engine + // can propagate deletes to other devices without leaving deleted + // entries to silently reappear at next pull. + FConn.ExecSQL( + 'CREATE TABLE IF NOT EXISTS entry_tombstones (' + + ' id INTEGER PRIMARY KEY AUTOINCREMENT,' + + ' user_id INTEGER NOT NULL,' + + ' uuid TEXT NOT NULL,' + + ' deleted_at DATETIME DEFAULT CURRENT_TIMESTAMP,' + + ' FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,' + + ' UNIQUE(user_id, uuid)' + + ')'); + FConn.ExecSQL( + 'CREATE INDEX IF NOT EXISTS idx_tombstones_user ' + + ' ON entry_tombstones(user_id, deleted_at DESC)'); // Per-folder customisation. NULL = no override → JS uses the default // accent + i-folder symbol. AddColumnIfMissing('folders', 'color', 'TEXT'); diff --git a/delphi-backend/UMainForm.pas b/delphi-backend/UMainForm.pas index 3460647..a9cea6e 100644 --- a/delphi-backend/UMainForm.pas +++ b/delphi-backend/UMainForm.pas @@ -18,6 +18,7 @@ interface uses System.SysUtils, System.Classes, System.UITypes, System.NetEncoding, System.StrUtils, System.Generics.Collections, System.IOUtils, System.JSON, + System.Net.HttpClient, System.Net.URLClient, Winapi.Windows, Winapi.ShellAPI, FMX.Forms, FMX.Controls, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Memo, FMX.Memo.Types, FMX.ScrollBox, FMX.Edit, FMX.Layouts, FMX.Types, @@ -370,6 +371,18 @@ begin // so we bypass the minimize-to-tray intercept in that case. if FQuitting then Exit; + // Windows shutdown / logoff / restart: WM_QUERYENDSESSION flipped the + // bridge's flag. Let the form close normally so FServer.Free and the + // FireDAC connection get a chance to checkpoint the WAL — otherwise + // Windows force-kills us at the shutdown timeout and we leave + // -shm / -wal files next to vault.db. + if Assigned(FBridge) and FBridge.ShutdownPending then + begin + FQuitting := True; + LogLine('System shutdown detected — closing normally.'); + Exit; + end; + // Otherwise: minimize to tray on close instead of quitting, so the vault // stays available without the dev-panel being visible. // When the server is stopped, allow normal close — there's no vault to @@ -932,6 +945,119 @@ begin BoolToStr(PM.AutoStart.IsAutoStartEnabled, True).ToLower + ')'); end + // ---- WebDAV remote sync (THTTPClient → WinHTTP, async) -------------- + // cmd://webdav/get | put | test ?reqId=&url=&user=&pwd=[&data=] + // Callback: Bridge.onWebdavResult(reqId, status, bodyOrError) + // - GET ok → status=200, body=base64 of response bytes + // - GET 404 → status=404, body='' (caller treats as "no remote yet") + // - PUT ok → status=200/201/204, body='' + // - test → status=200..399 means reachable, body='' + // Network errors → status=0, body=exception message. + else if (ACmd = 'webdav/get') or (ACmd = 'webdav/put') or (ACmd = 'webdav/test') then + begin + var LMethod := ACmd; + var LReqId := GetParam('reqId'); + var LUrl := GetParam('url'); + var LUser := GetParam('user'); + var LPwd := GetParam('pwd'); + var LData := GetParam('data'); + TThread.CreateAnonymousThread( + procedure + var + LHttp: System.Net.HttpClient.THTTPClient; + LResp: System.Net.HttpClient.IHTTPResponse; + LBodyStream: TBytesStream; + LReqStream: TBytesStream; + LBytes: TBytes; + LBodyB64: string; + LStatus: Integer; + LErr: string; + begin + LStatus := 0; + LBodyB64 := ''; + LErr := ''; + try + LHttp := System.Net.HttpClient.THTTPClient.Create; + try + LHttp.ConnectionTimeout := 10000; + LHttp.ResponseTimeout := 30000; + if (LUser <> '') then + begin + LHttp.CredentialsStorage.AddCredential( + System.Net.URLClient.TCredentialsStorage.TCredential.Create( + System.Net.URLClient.TAuthTargetType.Server, '', '', LUser, LPwd)); + end; + if LMethod = 'webdav/get' then + begin + LBodyStream := TBytesStream.Create; + try + LResp := LHttp.Get(LUrl, LBodyStream); + LStatus := LResp.StatusCode; + if (LStatus >= 200) and (LStatus < 300) and (LBodyStream.Size > 0) then + begin + SetLength(LBytes, LBodyStream.Size); + Move(LBodyStream.Bytes[0], LBytes[0], LBodyStream.Size); + LBodyB64 := TNetEncoding.Base64.EncodeBytesToString(LBytes); + LBodyB64 := StringReplace(LBodyB64, #13, '', [rfReplaceAll]); + LBodyB64 := StringReplace(LBodyB64, #10, '', [rfReplaceAll]); + end; + finally + LBodyStream.Free; + end; + end + else if LMethod = 'webdav/put' then + begin + LBytes := TNetEncoding.Base64.DecodeStringToBytes(LData); + LReqStream := TBytesStream.Create(LBytes); + try + LResp := LHttp.Put(LUrl, LReqStream); + LStatus := LResp.StatusCode; + finally + LReqStream.Free; + end; + end + else // webdav/test — HEAD is widely supported even when PROPFIND isn't + begin + LResp := LHttp.Head(LUrl); + LStatus := LResp.StatusCode; + end; + finally + LHttp.Free; + end; + except + on E: Exception do + begin + LStatus := 0; + LErr := E.Message; + end; + end; + TThread.Queue(nil, + procedure + var + LEscReq, LEscPayload: string; + begin + LEscReq := StringReplace(LReqId, '"', '\"', [rfReplaceAll]); + // GET success path → ship body base64. Otherwise the field + // carries either the empty string or the exception message + // (for status=0 network errors). + if (LMethod = 'webdav/get') and (LStatus >= 200) and (LStatus < 300) then + LEscPayload := LBodyB64 + else + LEscPayload := LErr; + LEscPayload := StringReplace(LEscPayload, '\', '\\', [rfReplaceAll]); + LEscPayload := StringReplace(LEscPayload, '"', '\"', [rfReplaceAll]); + LEscPayload := StringReplace(LEscPayload, #13, '', [rfReplaceAll]); + LEscPayload := StringReplace(LEscPayload, #10, '\n', [rfReplaceAll]); + WebBrowser.ExecuteJavaScript( + 'if(window.Bridge&&Bridge.onWebdavResult)' + + 'Bridge.onWebdavResult("' + LEscReq + '",' + + IntToStr(LStatus) + ',"' + LEscPayload + '")'); + LogLine(Format('%s %s → %d (%d bytes payload)', + [LMethod, LUrl, LStatus, Length(LEscPayload)])); + end); + end).Start; + end + // ---- Native file save (bypasses WebView2's browser download UI) ------ // JS sends: cmd://file/save?name=&data=&reqId= // Delphi opens GetSaveFileName, writes the decoded bytes, then calls diff --git a/delphi-backend/assets/assets.res b/delphi-backend/assets/assets.res index 5d846bb..7ab11e6 100644 Binary files a/delphi-backend/assets/assets.res and b/delphi-backend/assets/assets.res differ diff --git a/index.html b/index.html index 8fc16a1..7bd1e9c 100644 --- a/index.html +++ b/index.html @@ -646,6 +646,57 @@ + +