Files
r-zakarya 7440d07793 feat: profile avatar + tombstone-restore fix + WebView2 nav race + sync summary
Profile picture / avatar
- users.avatar_b64 column (nullable, cosmetic, not encrypted) + GET/POST
  /avatar endpoints mirroring the settings handler pattern.
- Top-right chip + Settings→Account show a round avatar: custom picture
  if set, otherwise the username's initial on a deterministic
  hash-picked colour (stable across renders).
- Upload downscales + center-crops to a 128px JPEG via FileReader →
  data: URI (NOT blob:, which the CSP's `img-src 'self' data:` blocks)
  before POSTing. Remove button clears it.
- Carried in the encrypted JSON export; restored on import only when the
  current account has no picture (never clobbers a local one).

Tombstone restore-then-sync fix
- POST /entries and POST /entries/bulk-import now DELETE any tombstone
  matching an inserted uuid (same transaction) so a restored backup
  isn't re-killed on the next sync by its own stale tombstone.
- applyRemoteSnapshot arbitrates remote tombstones by timestamp: a
  tombstone is skipped when the local entry with that uuid is newer than
  deleted_at (resurrection wins). Ties / unparseable timestamps favour
  KEEP. loadEntries() up front so updated_at reflects the live rows.

WebView2 navigation race
- Black-window-on-cold-start fix: the 1.5s nav timer no longer consumes
  FPendingURL when WebView2 isn't initialised yet (it re-arms, bounded
  to ~10 retries). FBrowserInitialized flag set in OnInitialized; after
  the retry budget we Navigate best-effort rather than loop forever.

Sync UX
- Bidirectional toast: "pulled X new · Y updated · Z deleted · pushed N
  entries" so a 0/0/0 pull still shows the vault was uploaded.
- FolderPOST/PUT: pre-declare ftString on color/icon params (fixes the
  earlier [SQLite]-335 on NULL bind, already in play for CSV import).

Docs
- CLAUDE.md sync section documents tombstone purge-on-insert +
  resurrection arbitration.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-02 23:36:36 +01:00

198 lines
5.2 KiB
ObjectPascal

unit PM.Handler.Settings;
(*
GET /settings -> {<arbitrary JSON object stored as-is>}
PUT /settings body: {<arbitrary JSON object>} -> {message:"OK"}
Persists a per-user preferences blob (users.settings_json). The server
treats the body as opaque JSON — schema lives in the JS layer. Any client
reading it should tolerate unknown keys for forward compatibility.
Device-specific toggles (quick-unlock DPAPI, autofill hotkey) deliberately
stay in localStorage on the client and are NOT included in this blob.
*)
interface
implementation
uses
System.SysUtils, System.JSON, System.Classes,
Data.DB, FireDAC.Comp.Client, FireDAC.Stan.Param,
IdCustomHTTPServer,
PM.Router, PM.JSON, PM.Session, PM.Database;
procedure HandleGetSettings(ARequest: TIdHTTPRequestInfo;
AResponse: TIdHTTPResponseInfo; const AParams: TArray<string>);
var
LUserId: Integer;
LQ: TFDQuery;
LRaw: string;
LObj: TJSONValue;
begin
LUserId := Authenticate(ARequest, AResponse);
DB.Lock;
try
LQ := TFDQuery.Create(nil);
try
LQ.Connection := DB.Connection;
LQ.SQL.Text := 'SELECT settings_json FROM users WHERE id = :uid';
LQ.ParamByName('uid').AsInteger := LUserId;
LQ.Open;
if LQ.IsEmpty then
LRaw := '{}'
else
LRaw := LQ.FieldByName('settings_json').AsString;
finally
LQ.Free;
end;
finally
DB.Unlock;
end;
if Trim(LRaw) = '' then LRaw := '{}';
// Validate so a corrupt row doesn't return malformed JSON to the client.
LObj := TJSONObject.ParseJSONValue(LRaw);
if LObj = nil then LObj := TJSONObject.Create;
TJSONHelper.SendJSON(AResponse, LObj); // SendJSON frees the object
end;
procedure HandlePutSettings(ARequest: TIdHTTPRequestInfo;
AResponse: TIdHTTPResponseInfo; const AParams: TArray<string>);
var
LUserId: Integer;
LBody: TJSONObject;
LSerialized: string;
LQ: TFDQuery;
begin
LUserId := Authenticate(ARequest, AResponse);
RequireCSRF(ARequest, AResponse, LUserId);
LBody := TJSONHelper.ReadBody(ARequest);
try
// Re-serialize to a canonical compact form (strips comments / extra
// whitespace, and guarantees what we store is valid JSON).
LSerialized := LBody.ToJSON;
finally
LBody.Free;
end;
// Soft cap to protect the row from a runaway client (typical settings
// blob is a few hundred bytes; 16 KB leaves room for future flags).
if Length(LSerialized) > 16384 then
begin
TJSONHelper.SendError(AResponse, 413, 'Settings payload too large');
Exit;
end;
DB.Lock;
try
LQ := TFDQuery.Create(nil);
try
LQ.Connection := DB.Connection;
LQ.SQL.Text := 'UPDATE users SET settings_json = :s WHERE id = :uid';
LQ.ParamByName('s').AsString := LSerialized;
LQ.ParamByName('uid').AsInteger := LUserId;
LQ.ExecSQL;
finally
LQ.Free;
end;
finally
DB.Unlock;
end;
TJSONHelper.SendOK(AResponse);
end;
// GET /avatar -> { avatar_b64: <data-uri or ''> }
// Fetched once at login (enterApp) so the image isn't re-sent on every
// settings save.
procedure HandleGetAvatar(ARequest: TIdHTTPRequestInfo;
AResponse: TIdHTTPResponseInfo; const AParams: TArray<string>);
var
LUserId: Integer;
LQ: TFDQuery;
LObj: TJSONObject;
LVal: string;
begin
LUserId := Authenticate(ARequest, AResponse);
DB.Lock;
try
LQ := TFDQuery.Create(nil);
try
LQ.Connection := DB.Connection;
LQ.SQL.Text := 'SELECT avatar_b64 FROM users WHERE id = :uid';
LQ.ParamByName('uid').AsInteger := LUserId;
LQ.Open;
if LQ.IsEmpty then LVal := '' else LVal := LQ.FieldByName('avatar_b64').AsString;
finally
LQ.Free;
end;
finally
DB.Unlock;
end;
LObj := TJSONObject.Create;
LObj.AddPair('avatar_b64', LVal);
TJSONHelper.SendJSON(AResponse, LObj);
end;
// POST /avatar body: { avatar_b64: <data-uri> } ('' clears it)
procedure HandleSetAvatar(ARequest: TIdHTTPRequestInfo;
AResponse: TIdHTTPResponseInfo; const AParams: TArray<string>);
var
LUserId: Integer;
LBody: TJSONObject;
LVal: string;
LQ: TFDQuery;
begin
LUserId := Authenticate(ARequest, AResponse);
RequireCSRF(ARequest, AResponse, LUserId);
LBody := TJSONHelper.ReadBody(ARequest);
try
LVal := LBody.GetValue<string>('avatar_b64', '');
finally
LBody.Free;
end;
// Cap ~700 KB base64 (~512 KB raw) — the client downscales to a small
// square before upload, so anything larger is a bug or an attack.
if Length(LVal) > 720000 then
begin
TJSONHelper.SendError(AResponse, 413, 'Avatar too large');
Exit;
end;
DB.Lock;
try
LQ := TFDQuery.Create(nil);
try
LQ.Connection := DB.Connection;
LQ.SQL.Text := 'UPDATE users SET avatar_b64 = :a WHERE id = :uid';
LQ.ParamByName('a').DataType := ftMemo;
if LVal = '' then LQ.ParamByName('a').Clear
else LQ.ParamByName('a').Value := LVal;
LQ.ParamByName('uid').AsInteger := LUserId;
LQ.ExecSQL;
finally
LQ.Free;
end;
finally
DB.Unlock;
end;
TJSONHelper.SendOK(AResponse);
end;
initialization
Router.Register('GET', '/settings', HandleGetSettings);
Router.Register('PUT', '/settings', HandlePutSettings);
Router.Register('GET', '/avatar', HandleGetAvatar);
Router.Register('POST', '/avatar', HandleSetAvatar);
end.