Files
Password-Manager/delphi-backend/Handlers/PM.Handler.Settings.pas
T
Zaki 40b3154a34 feat: MFA tools, single-instance, tray polish, prefs persistence
Session highlights:

- feat(prefs): DPAPI-backed key/value store (PM.UserPrefs) — fixes
  rememberedUsername being lost across reboots due to the random
  ephemeral HTTP port changing the localStorage origin every launch.
  Bridge cmd://prefs/{get,set} round-trips through Delphi.

- feat(tray): icon visible from startup (NIM_ADD at constructor, not
  at first minimize). Tray context menu themed via uxtheme!135
  SetPreferredAppMode so it follows the app's dark/light setting.

- feat(single-instance): named mutex + RegisterWindowMessage broadcast.
  Second launch posts WM_PMSHOW to HWND_BROADCAST and exits; the
  running bridge restores the window from tray. Mutex lives in Local\
  namespace so distinct Windows users can still each run one.

- feat(mfa): Authenticator sidebar view (live TOTP codes for every
  entry with a secret) + standalone TOTP generator modal (paste
  base32 / otpauth:// URI, or generate a random 20-byte secret).

- feat(sidebar): Folders / Tags / Tools sections collapsible with
  chevron toggle. Badge counts stay visible when collapsed. State
  persisted in settings_json (synced across devices).

- feat(autofill): hotkey when vault is locked now restores the app
  and focuses the master password input instead of no-op'ing
  silently. Cleaner UX for the common "I hit Ctrl+Shift+L but the
  vault was locked" path.

- feat(quick-unlock): when enabled, skip lockVault on Windows lock /
  sleep. Rationale: the DPAPI blob already gates access via the
  Windows account, so re-locking on top of the OS lock is redundant.
  Idle auto-lock still fires (separate opt-in).

- fix(quick-unlock): re-sync state.quickUnlockEnabled from DPAPI
  source-of-truth at boot, instead of trusting (now-volatile)
  localStorage.

- docs: CLAUDE.md updated with all new modules, bridge commands,
  and the port-ephemeral pitfall.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-08 21:31:39 +01:00

114 lines
3.0 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;
initialization
Router.Register('GET', '/settings', HandleGetSettings);
Router.Register('PUT', '/settings', HandlePutSettings);
end.