Commit Graph

122 Commits

Author SHA1 Message Date
Zaki 01c56edf25 feat(recovery): single-use recovery code for forgotten master password
In a zero-knowledge vault, forgetting the master password normally
means losing the data — the AES key is derived from the master pw
and the server can't help. This commit adds the standard escape
hatch: a one-time recovery code that key-wraps the AES key so the
user can get back in.

Threat model
============
The plaintext recovery code is shown to the user exactly once, at
generation time. Server only ever stores SHA-256(code) + an AES-GCM
wrap of the vault key under a KEK = PBKDF2(code, kdf_salt, 600k).
Without the plaintext code the server cannot unwrap. The code is
high-entropy (96 bits from a 32-char ambiguity-free alphabet, in 4
groups of 4) — printed form is misreading-resistant.

Single use: redeeming deletes the row inside the same DB.Lock the
lookup happened in, so concurrent redeem attempts are race-free.
Failed redemptions feed both the per-IP rate limit AND the per-
username lockout, so brute-forcing the code is infeasible.

Schema
======
recovery_keys (
  user_id      INTEGER PRIMARY KEY (1:1 with users, FK cascade),
  code_hash    TEXT NOT NULL          (SHA-256 hex of plaintext code),
  kdf_salt     TEXT NOT NULL          (PBKDF2 salt for KEK derivation),
  wrapped_key  TEXT NOT NULL          (base64 AES-GCM ciphertext of vault key),
  wrapped_iv   TEXT NOT NULL          (base64 12B IV for the wrap),
  created_at   DATETIME DEFAULT CURRENT_TIMESTAMP
)

Backend: new unit PM.Handler.Recovery
=====================================
  GET    /recovery-key/status   (auth)         -> { configured, created_at? }
  POST   /recovery-key/setup    (auth + CSRF)  body {masterPassword, codeHash,
                                                     kdfSalt, wrappedKey, wrappedIv}
  DELETE /recovery-key          (auth + CSRF)  -> remove config
  POST   /recovery-key/redeem   (NO auth)      body {username, code}
                                               -> session + wrappedKey + wrappedIv + kdfSalt
                                                  + user's current salt + kdfIterations

VerifyMasterPassword() helper handles both legacy 'pbkdf2' and
current 'pbkdf2-sha256' schemes consistently with PM.Handler.Auth.

Setup flow
==========
1. Settings → "Generate recovery code" button (asks master pw via reauth).
2. Client generates: 16-char code + fresh kdf_salt + exports the current
   AES key via crypto.subtle.exportKey('raw').
3. Client wraps the raw key under KEK=PBKDF2(code, kdf_salt, 600k)
   with a random 12B IV → base64.
4. POSTs to /recovery-key/setup. Server verifies master pw, INSERT-or-
   replaces the row (DELETE+INSERT, no UPSERT — same pattern as the
   lockout table since FireDAC's UPSERT support is patchy).
5. Confirm modal shows the plaintext code in a monospace, user-select-all
   panel. The modal is forcing: "I saved it" button is the only way out.
   Modal is the only place the code ever appears — server never sees it.

Redeem flow (forgot master pw)
==============================
1. Auth screen → "Forgot master password? Use a recovery code" link.
2. promptDialog: username, then code (masked input).
3. POST /recovery-key/redeem. Server hashes the typed code, joins with
   users by username, ConstantTimeEquals against stored hash. On match:
     - deletes the recovery_keys row (single-use)
     - issues a fresh session token + CSRF
     - returns: { token, csrfToken, salt, kdfIterations, kdfSalt,
                  wrappedKey, wrappedIv, userId }
4. Client unwraps the AES key with PBKDF2(code, kdfSalt, 600k) → raw bytes
   → importKey('raw') back into a CryptoKey.
5. State is reconstituted from the new session, persistCryptoKey, enterApp.
6. Client immediately opens the Change-master-password modal — the
   recovery code is consumed and the account needs a fresh master pw
   AND a fresh recovery code (the user generates a new one from Settings).

Backward compat
===============
Recovery is opt-in. Existing users see "No recovery key set" in Settings
until they generate one. No migration needed — the table is created via
CREATE TABLE IF NOT EXISTS at server startup, FK cascade on user delete.

Minor UI additions
==================
 - .btn-link CSS class for the auth-screen "Forgot master password?" link.
 - Recovery-status label in Settings refreshed on every openSettings()
   via GET /recovery-key/status.
2026-05-23 11:18:34 +01:00
Zaki cca8184b81 feat(auth): change master password with full vault re-encryption
Adds the canonical PM feature: let the user pick a new master password
and have every entry transparently re-encrypted under the new key,
without ever exposing plaintext to the server.

Backend endpoint: POST /change-master-password
==============================================
Body:
  {
    currentMasterPassword,   verified against current stored hash
    newMasterPassword,       basis for the new hash + new client key
    newSalt,                 64-char hex, client-generated
    entries: [{ id, encrypted_password, iv,
                totp_secret?, totp_iv? }, ...]
  }

Flow:
  1. Authenticate + RequireCSRF (caller already logged in).
  2. RejectIfAccountLocked — pw change is brute-forceable through a
     hijacked session, so it respects the same per-account lockout as
     /login.
  3. Verify currentMasterPassword against the stored hash. Branches on
     hash_algo to handle both legacy 'pbkdf2' and current 'pbkdf2-sha256'.
     Wrong pw → RecordFailedAccountAttempt + audit + 401.
  4. Compute new auth hash = SHA256(PBKDF2(new_pw, new_salt, 600k)),
     always using the current scheme (migration baked in).
  5. ATOMIC transaction:
       UPDATE users SET password_hash, salt, kdf_iterations, hash_algo
       UPDATE vault_entries SET encrypted_password, iv, totp_secret, totp_iv
       (per entry)
     Any failure → rollback, user stays on the old config.
  6. DeleteAllUserSessions — every OTHER session is invalidated so a
     leaked old token can't keep working past the rotation. The current
     caller's session stays valid.
  7. ClearAccountLockout + audit_log entry.
  8. Returns { message, salt, kdfIterations }.

Client
======
New modal in index.html (#changeMasterModal) with three password
fields (current / new / confirm) + inline error display. Added a
"Change master password" button in the Settings panel → Account
section. Escape-key handler routes through it like the other modals.

doChangeMasterPassword():
  1. Local validation: all fields filled, new ≥ 8 chars, new == confirm,
     new ≠ current. Fast failure beats a round trip.
  2. randomHexSalt() → 32 secure random bytes, hex-encoded.
  3. Derive newKey = PBKDF2(new_pw, new_salt, 600k).
  4. Walk state.entries: decrypt password + (optional) TOTP under the
     current key, re-encrypt under newKey with fresh random IVs.
     One decrypt failure aborts the whole change — better than partial
     commit.
  5. POST to /change-master-password.
  6. On success: swap state.salt + state.cryptoKey, persistCryptoKey,
     update sessionStorage, refresh cached ciphertexts in state.entries,
     close modal, toast.
  7. On 401 / 429 / generic error: show inline error in the modal so
     the user can fix and retry without re-typing everything.

Threat model notes
==================
 - The current session token stays valid because the new server hash
   only invalidates OTHER sessions. Self-logout would be needlessly
   disruptive (user already proved knowledge of both pws).
 - Server still sees the old + new master pws transiently in /change-
   master-password. Same trade-off as /login — eliminating it requires
   redesigning to send pre-computed verifiers (SRP-style), tracked
   separately.
 - The salt rotates with the password — best-practice against any
   precomputed dictionary attack tied to the previous salt.
2026-05-23 11:11:38 +01:00
Zaki 3c786366fc feat(export): encrypt vault backups with an independent password
Replaces the plaintext JSON exporter with an encrypted container.
The previous plaintext flow was a known security gap — a backup file
on disk or in a cloud sync folder gave full plaintext access to
every password if accessed by anyone (or anything) other than the
user.

Container format
================
Self-describing JSON:
  {
    "format":         "pm-encrypted-export-v1",
    "kdf":            "pbkdf2-sha256",
    "kdf_iterations": 600000,
    "kdf_salt":       "<base64 32B>",
    "iv":             "<base64 12B>",
    "ciphertext":     "<base64 AES-GCM(payload)>",
    "created_at":     "<ISO>"
  }
payload = same shape as the legacy plaintext exporter (entries array
with site, username, password, folder, tags, favorite, totp_secret,
timestamps), so the round-trip through the JSON importer works
without a separate code path.

Export password
===============
User-chosen, INDEPENDENT of the master password — the export modal
explicitly explains this. Rationale:
 - A master-password change doesn't invalidate old backups.
 - The backup file can be shared with another person without
   revealing the master pw.
 - Trade-off: one more password for the user to remember. We assume
   they're storing the backup intentionally and can record the pw.
Minimum length 6 enforced client-side.

Flow
====
Export:
  1. askReauth(master pw) → server /reauth verifies (defense against
     someone reaching the unlocked laptop and dumping the vault).
  2. promptDialog(password: true) → export password.
  3. Walk state.entries, decrypt each password + TOTP with the vault
     key, assemble payload.
  4. encryptExportPayload(payload, exportPwd) — random 32B salt,
     random 12B IV, PBKDF2 600k, AES-GCM-256.
  5. Download the container as
     vault-export-YYYY-MM-DD.json.

Import:
  1. Read file, detect format. JSON with format === "pm-encrypted-
     export-v1" → prompt for the export password.
  2. decryptExportContainer → plaintext payload, then JSON.stringify
     back into the existing parseEntriesFromJSON path so the rest of
     the import flow (preview confirm, bulk encrypt, /entries/bulk-
     import) is unchanged.
  3. Wrong password → AES-GCM tag fails → "Decryption failed" toast,
     user retries.

Other changes
=============
 - promptDialog gains a `password: true` option that flips the
   confirm input's type so the value is masked on screen.
 - Export modal copy in the Settings panel updated to mention the
   encrypted format and the independent password.
 - The 429-lockout path on /reauth is now handled explicitly in
   doExport (was previously falling through to "wrong password").

Backward compatibility
======================
Plaintext JSON exports produced by the previous version still
import — parseEntriesFromJSON doesn't care whether the input came
from a fresh decryption or directly from a plaintext file. The
exporter no longer produces plaintext though; users with old
backups should re-export after upgrading.
2026-05-23 05:35:03 +01:00
Zaki 4b15811221 feat(import): JSON / CSV vault import with heuristic column mapping
Round-trip companion to the existing doExport(). Supports two file
formats with auto-detection (extension + first-char sniff):

JSON
====
Native shape produced by doExport() AND a forgiving fallback for any
flat array of entry objects with site/url + password fields. Accepts:
  - { version, exported_at, entries: [...] }   (native)
  - [{ ... }, { ... }]                          (flat array)
  - mixed keys: site|url|name, username|user|login|email, etc.

CSV
===
RFC-4180-ish parser (~30 lines): quoted fields, escaped "", commas
inside quotes, CRLF line endings. No streaming since password-manager
imports are realistically MB-scale at most.

Heuristic column mapping (case + underscore tolerant) covers the
common exporters out of the box:

  Site/URL     : name, title, url, site, website, login_uri, login_url
  Username     : login_username, username, user, login, email
  Password     : login_password, password, pass, pwd
  Folder       : folder, group, category, path, collection
  Tags         : tags, labels (comma/semicolon-split)
  Notes        : notes, note, comment    (short notes joined into tags)
  TOTP         : login_totp, totp, otpauth, authenticator, two_factor

If the TOTP column holds a full otpauth:// URI it's parsed and only
the secret param is stored — same path used by the slide-over TOTP
field. Invalid base32 TOTP secrets are dropped silently rather than
failing the whole import.

Backend
=======
New endpoint: POST /entries/bulk-import
Body: { entries: [{ site, username, encrypted_password, iv, folder,
                    tags, totp_secret, totp_iv }, ... ] }
Caps at 10,000 entries per request as a sanity bound. Inserts inside
a single SQLite transaction — partial failure rolls back cleanly, the
user retries from the same source file. Returns { imported: N }.

Rows missing site or ciphertext are skipped within the transaction
(not failed) so one bad row in a 500-entry import doesn't blow up
the whole batch.

Client flow
===========
doImport():
  1. Hidden <input type="file" accept=".json,.csv"> picker
  2. Read text, detect format, route to parseEntriesFromJSON or CSV
  3. confirmDialog preview: count + first 3 sample sites + skipped rows
  4. On confirm: encryptImportEntry() each plaintext entry with the
     current vault key (reuses encryptPwd / base32Decode validation)
  5. Single POST to /entries/bulk-import
  6. Reload entries, refresh UI, trigger HIBP scan if enabled

UI
==
Two entry points (mirroring Export):
 - Sidebar "Import vault" nav item, next to "Export vault"
 - Settings panel "Import" section with descriptive blurb
Both call doImport(). New i-log-in icon added to the SVG sprite (mirror
of i-log-out used by Export).

Limitations
===========
 - No de-duplication: importing the same file twice yields duplicate
   entries. Trade-off to keep the v1 simple — the user can sort it
   out with the existing trash/multi-select UI.
 - No password-protected vault formats (Bitwarden encrypted JSON,
   KeePass kdbx). Only plaintext exports — same trade-off as
   doExport() which produces plaintext JSON.
2026-05-23 05:30:08 +01:00
Zaki 60aa106a30 fix(crypto): SHA-256 wrap auth hash so vault.db at rest no longer = AES key
THE PROBLEM
===========
Before this commit, users.password_hash stored on the server contained
PBKDF2(pw, salt, iters) in hex — the exact same 32 bytes the client
uses as the AES-GCM key to encrypt every entry. Anyone who got hold of
vault.db (filesystem access, backup leak, etc.) had the encryption key
in their hand, no brute force needed. The increased PBKDF2 iteration
count from the previous commit helped against the cipher-text path,
but the easier path was right there in the user row.

THE FIX
=======
Wrap the PBKDF2 output in SHA-256 before storing:

  password_hash = SHA256(PBKDF2(pw, salt, iters))

SHA-256 is one-way. The stored hash can still be verified at login
(server recomputes PBKDF2 from the posted master pw, then SHA-256s it,
compares to stored), but the AES key can no longer be recovered from
it. At rest, vault.db only contains an irreversible derivative.

The server still sees pw transiently during /login while computing
the comparison — eliminating that requires a redesigned auth
protocol where the client sends a pre-computed verifier (SRP, OPAQUE,
or simply SHA-256(PBKDF2(pw, salt, iters)) sent from the client).
That's a separate, larger refactor. This commit closes the at-rest
hole, which is the realistic attack surface for vault file leaks.

SCHEMA / MARKER
===============
users.hash_algo distinguishes the two schemes:
  'pbkdf2'        — LEGACY (raw hex, = AES key)
  'pbkdf2-sha256' — CURRENT (SHA-256-wrapped, one-way)

A constant HASH_ALGO_CURRENT replaces the string literal everywhere
to avoid silent drift between the writer and the reader sides.

MIGRATION
=========
Folded into the existing /migrate-kdf endpoint introduced for the
100k→600k iteration bump. Login response now signals migration on
EITHER:
  - kdf_iterations < PBKDF2_ITERATIONS_TARGET, OR
  - hash_algo != 'pbkdf2-sha256'

The endpoint handles both transitions in one atomic transaction:
  UPDATE users SET password_hash = SHA256(PBKDF2(pw, salt, 600k)),
                   kdf_iterations = 600000,
                   hash_algo = 'pbkdf2-sha256'
  UPDATE vault_entries SET encrypted_password, iv (per entry, if KDF changed)

Idempotency tightened: the "already at target" short-circuit now
requires BOTH conditions, not just the iteration count. Without this,
users who migrated KDF before this commit landed would have been
stuck on the legacy hash format.

CLIENT
======
runKdfMigration() branches on whether the KDF actually changed:
  - kdfChange (fromIters !== toIters): re-encrypt all entries with the
    new key, send them in the entries array, swap state.cryptoKey on
    success. Shows "Vault security upgraded" toast.
  - !kdfChange (hash format only): skip the entry re-encryption loop
    entirely, send entries: []. Silent — the user didn't perceive a
    weakness change worth toasting about.

LOGIN / REAUTH
==============
Both now branch on hash_algo to pick the right verifier:
  HASH_ALGO_LEGACY  → ConstantTimeEquals(stored, PBKDF2(pw, salt, iters))
  HASH_ALGO_CURRENT → ConstantTimeEquals(stored, SHA256(PBKDF2(pw, salt, iters)))

Same constant-time comparison helper as before. Same legacy bcrypt
fallback (still 501-not-implemented).

ALL THREE SCENARIOS AFTER THIS COMMIT
=====================================
1. New register: starts at HASH_ALGO_CURRENT + 600k. No migration ever.
2. Legacy 100k + 'pbkdf2': full migration on next login (hash format
   + iter count + entry re-encryption) in one transaction.
3. Mid-state (already-migrated KDF + still-'pbkdf2'): hash format
   upgrade only on next login, no entry re-encryption.
2026-05-23 05:19:39 +01:00
Zaki cf94f67488 feat(2fa): TOTP secret storage + live 6-digit code generation
Adds RFC 6238 TOTP (Google Authenticator-style) support to every entry.
The secret is encrypted client-side with the same AES-GCM key as the
password — the server stores opaque ciphertext and never sees the
plaintext base32 secret.

Schema
======
vault_entries.totp_secret TEXT  -- AES-GCM ciphertext, base64
vault_entries.totp_iv     TEXT  -- 12-byte IV, base64
Both NULL when the entry has no 2FA configured. Added via
ApplyMigrations.AddColumnIfMissing so existing vaults migrate cleanly.

Backend
=======
HandleListEntries: includes totp_secret + totp_iv in the response (or
JSON null when not configured).
HandleCreateEntry / HandleUpdateEntry: accept both fields; empty string
in the body → server stores NULL. Clearing the secret removes 2FA
from the entry.

Frontend
========
TOTP primitives (pure crypto.subtle, no external lib):
 - base32Decode(s)         — RFC 4648, tolerates spaces / lowercase
 - generateTOTP(secret)    — HMAC-SHA1 + RFC 4226 dynamic truncation
 - parseOtpAuthUri(raw)    — extracts ?secret from otpauth:// URIs

UI in the slide-over (the canonical entry detail view):
 - New "Two-factor (TOTP)" field below the password row.
 - Input is password-masked by default with eye-toggle to reveal.
 - Pasting a full otpauth:// URI auto-extracts the secret param so the
   user can copy directly from a QR-code scanner without manual cleanup.
 - X button clears the secret (= removes 2FA on next save).
 - Live code panel below: large monospace "123 456" + Copy button
   (routes through Bridge.copySecure → secure clipboard + 30s auto-clear).
 - Linear progress bar drains over the 30s window, turns red < 5s.
 - Refresh tick runs once per second while the slide-over is open;
   stops on closeSlideOver to avoid background work.

Entry card meta now shows a "2FA" chip when totp_secret is non-null —
quick visual scan for which accounts have 2FA configured without
opening the slide-over.

Validation
==========
soSave calls base32Decode(secret) before encrypting to refuse obviously
broken input. Otherwise garbled base32 would save fine and only fail
in the code panel next time.

Migration interaction (KDF 100k→600k)
=====================================
KNOWN MINOR ISSUE: /migrate-kdf only re-encrypts encrypted_password+iv,
not totp_secret+totp_iv. In practice this is harmless because:
  1) KDF migration runs immediately after login on legacy accounts —
     before the user has a chance to add a TOTP secret.
  2) New accounts start at 600k iterations, no migration ever needed.
A legacy user who somehow added a TOTP between login and the
background migration completing would end up with a TOTP encrypted
under the old key. The fix (extend /migrate-kdf to re-encrypt TOTP
fields too) is a one-line follow-up if anyone hits the edge case.
2026-05-23 05:13:50 +01:00
Zaki a45897c33d feat(security): HIBP password breach check + CSP tightening
HIBP integration
================
Opt-in (default OFF) password breach check via the Have I Been Pwned
range API. The full master / entry password never leaves the machine —
only the first 5 characters of its SHA-1 hash. HIBP returns ~500
candidate suffixes; the client matches its own suffix locally.

UI:
 - New "Check passwords against breach database (HIBP)" toggle in
   Settings → Security with an explainer hint about k-anonymity.
 - On enable: background batch scan of all entries, results cached in
   state.hibpResults keyed by entry id. Concurrency capped at 6 to
   avoid hammering HIBP / hitting browser connection limits.
 - Entry cards show a red "Pwned" chip + breach count in the tooltip
   when count > 0. New i-alert icon added to the SVG sprite.
 - Auto-scan triggered after every enterApp() when the toggle is on.

Functions added to app.js:
 - sha1Hex(text)                       — crypto.subtle wrapper
 - hibpCheckPassword(plaintext)        — single-password check, returns count
 - hibpCheckAllEntries()               — batched scan over state.entries

The "Add-Padding: true" header is sent on every range request to defeat
the response-size side-channel (HIBP adds 800-1000 random extra entries
so an observer counting bytes can't narrow the prefix queried).

CSP tightening
==============
Audited the served HTML: zero <script> tags inline, only the external
js/app.js. Removed 'unsafe-inline' from script-src — real XSS defense.

Kept 'unsafe-inline' on style-src for now because index.html contains
inline style="" attributes and app.js calls element.style.cssText
extensively. Refactoring to CSS classes is a separate cleanup. Style
injection alone cannot execute code, so the residual risk is bounded
to visual manipulation in a single-user loopback app.

Added api.pwnedpasswords.com to connect-src as the only allowed
external origin (required by the HIBP feature above). Default still
'self' — everything else stays loopback.

Before:
  script-src 'self' 'unsafe-inline';
  style-src  'self' 'unsafe-inline';
  connect-src 'self';

After:
  script-src 'self';
  style-src  'self' 'unsafe-inline';
  connect-src 'self' https://api.pwnedpasswords.com;
2026-05-23 05:05:50 +01:00
Zaki e0e452306e feat(crypto): PBKDF2 iterations 100k → 600k with transparent re-encryption
Bumps the PBKDF2-SHA256 iteration count from 100,000 (OWASP 2017) to
600,000 (OWASP 2023). 6x slowdown on every brute-force attempt against
either the server-stored auth hash OR the AES-GCM ciphertext of the
entries — both currently use the same PBKDF2 output (see KNOWN ISSUE
below for why that's another problem to fix later).

Schema
======
users.kdf_iterations INTEGER DEFAULT 100000
  Per-user iteration count. Legacy rows predating the column default
  to 100k via the DEFAULT clause. New accounts insert 600k explicitly.

Migration flow
==============
Atomic from the user's perspective. No partial state ever persisted.

  1. /login (or /reauth):
     server reads users.kdf_iterations and verifies the master pw at
     that count. Login succeeds at the legacy strength. Response now
     includes kdfIterations (current) and optionally kdfMigration =
     { target: 600000 } when an upgrade is recommended.

  2. Client:
     derives the AES key at the OLD count to decrypt current entries
     (state.cryptoKey). enterApp() loads the vault normally.

  3. runKdfMigration() (background, after enterApp):
     - derives the NEW key at target iterations
     - decrypts every entry with the old key
     - re-encrypts every entry with the new key + fresh random IVs
     - POSTs { masterPassword, entries: [...] } to /migrate-kdf

  4. /migrate-kdf (new endpoint):
     - verifies the master pw against the OLD hash
     - in a single transaction:
        UPDATE users  SET password_hash = pbkdf2(pw, salt, 600k),
                          kdf_iterations = 600000
        UPDATE vault_entries SET encrypted_password, iv (per entry)
     - on any failure: ROLLBACK. User stays at legacy config, retries
       at next login. No half-migrated state possible.

  5. Client (post-commit):
     swaps state.cryptoKey to the new key, persists it, updates the
     cached ciphertext in state.entries, shows a "Vault security
     upgraded" toast.

Idempotency: server's /migrate-kdf short-circuits with "Already at
target" if users.kdf_iterations >= PBKDF2_ITERATIONS_TARGET.

Race conditions: two concurrent migrations from two tabs both
recompute the SAME new key (deterministic PBKDF2). The losing
transaction's entries get re-encrypted with the winning one's IVs,
but both clients can decrypt because the keys are identical.

KNOWN ISSUE (not fixed by this commit)
======================================
The server's password_hash IS the client's AES key, in hex form —
both sides compute PBKDF2(pw, salt, iters) and store/use the same
32 bytes. This means a stolen vault.db gives the attacker the
encryption key directly, without needing to brute-force anything.
The 100k → 600k bump still helps because the AES-GCM ciphertext
itself is also a brute-force target, but the architectural fix
(server stores SHA256(aes_key) instead of aes_key in hex) is a
separate concern that needs its own migration.

Other changes
=============
 - HandleRegister: new accounts insert kdf_iterations=600000.
 - HandleReauth: response upgraded to JSON with kdfIterations
   + optional kdfMigration. Unlock path now also triggers migration.
 - SendAuthSuccess: extended signature, all callers updated.
 - deriveKey(pwd, saltHex, iterations) in app.js: iterations param
   required, defaults to 100000 for back-compat with any legacy caller.
2026-05-23 04:54:05 +01:00
Zaki bff9bdf9f2 feat(bridge): auto-lock on sleep/hibernate + fix UPSERT syntax
Sleep/hibernate handling
========================
Adds WM_POWERBROADCAST / PBT_APMSUSPEND handling alongside the existing
WTS_SESSION_LOCK detection. Closing a laptop lid often suspends the
system without firing a session lock, leaving the decrypted vault in
memory until resume — this fixes that.

Implementation note: WM_POWERBROADCAST is normally only delivered to
top-level windows, and Windows can silently skip hidden utility windows.
PowerRegisterSuspendResumeNotification (user32, Win 8+) forces delivery
to our specific HWND regardless. Loaded dynamically via GetProcAddress
so older Windows degrades gracefully (WTS lock still works).

The suspend handler reuses OnSystemLock — semantically the same event
from the user's perspective ("I'm leaving the machine"). Calls
lockVault() in JS via ExecuteJavaScript.

RateLimit fix (related: lockout feature from previous commit)
=============================================================
The UPSERT (INSERT ... ON CONFLICT DO UPDATE) in RecordFailedAccountAttempt
errored with "near ON: syntax error" — either the bundled SQLite version
or FireDAC's parameter preprocessor doesn't handle UPSERT correctly.
Replaced with portable UPDATE-then-INSERT (safe under our DB.Lock).

Also:
 - datetime modifier ("+60 seconds") built in Delphi via Format() rather
   than SQL-side concatenation ('+' || :sec || ' seconds'), which FireDAC
   was mangling on some configs.
 - GetAccountLockoutRemaining rewritten with julianday() (the SQLite
   idiom for date arithmetic) instead of strftime('%s'). Cleaner, NULL-safe.
2026-05-23 00:29:21 +01:00
Zaki 9f6636defc feat(auth): per-account brute-force lockout with exponential backoff
Existing protection was per-IP only (login_attempts table). On a loopback
deployment everyone hits 127.0.0.1, so the per-IP counter is mostly
ornamental — the real attacker is on the same machine. Adds a second
defense layer that tracks failures per username with an exponential
backoff schedule.

Schema:
  account_lockouts (username TEXT PK, failed_count INT,
                    locked_until DATETIME, last_attempt_at, last_attempt_ip)

Backoff after threshold (4+ failures):
  1, 2, 3 failures → no lockout (grace window for typos)
  4th             → 60 s
  5th             → 5 min
  6th             → 15 min
  7th             → 1 h
  8th             → 6 h
  9th and beyond  → 24 h (capped)

Counter resets to 0 on successful login or reauth. Old non-locked rows
older than 30 days are pruned by CleanupExpired alongside the existing
sessions / audit_log / login_attempts cleanups.

Wiring:
 - HandleLogin / HandleReauth both check RejectIfAccountLocked() before
   touching the users table. Lockout responses are 429 with JSON body
   { error, retry_after } and a Retry-After header.
 - Failed attempts are recorded against the username even when the user
   doesn't exist, preventing account enumeration via differential
   "is this account locked?" probes.
 - PBKDF2 hash comparison was already constant-time (ConstantTimeEquals);
   no change there.

Client (js/app.js):
 - api() now preserves response status + body on Error so callers can
   distinguish 429-lockout from other errors.
 - New showLockoutCountdown(seconds) renders a live "Account locked —
   try again in Xm Ys" message in #authHint, disables #loginBtn until
   the countdown reaches 0, then re-enables it.
 - doLogin / doUnlock both branch on err.status === 429 + retry_after
   to call showLockoutCountdown instead of a generic error toast.

Known limitation: an attacker can DoS-lock arbitrary usernames by
spamming /login with that name. This is intentional — the alternative
(per-(username,IP) tracking) would let attackers enumerate accounts.
DoS-lock is acceptable; auth bypass is not.
2026-05-23 00:14:44 +01:00
Zaki 519e8fbd48 chore: untrack vault.db (contains user secrets)
vault.db was tracked from the start of the repo, meaning every commit
since the initial import has captured snapshots of the user's password
data. Even though entries are AES-GCM encrypted in the DB, the file
also contains:
  - PBKDF2 salt + hash of the master password (offline-crackable)
  - Audit log with timestamps + IP addresses
  - Session tokens (transient but historical)
  - Login attempt counters per username

Future commits no longer include vault.db. The Delphi/PHP backend
auto-creates the schema via CREATE TABLE IF NOT EXISTS on first run,
so a fresh clone needs no migration step.

Also ignore the SQLite sidecar files (-journal, -wal, -shm).

NOTE: this only stops future leaks. The historical commits still
contain old snapshots. Purging history requires git filter-repo +
force-push, which rewrites every commit hash and breaks existing
clones. See README for instructions if a history purge is desired.
2026-05-23 00:07:00 +01:00
Zaki 506aee7e6f feat: Delphi backend + JS↔Delphi bridge (clipboard, tray, auto-lock)
Introduces the Delphi 12 FMX backend (PMServer) that hosts the embedded
WebView2 vault on 127.0.0.1, and a native bridge between JS and Delphi
that wires three privacy-focused features:

1. Secure clipboard
   Copying a password registers the Win32 "ExcludeClipboardContentFromMonitorProcessing"
   format alongside CF_UNICODETEXT, so Win+V clipboard history never sees
   the value. Auto-clears after 30s via TTimer. Bridge.copySecure() in
   app.js routes all password/username/secret copy paths through the
   native layer when running inside the Delphi WebView2 (falls back to
   navigator.clipboard for the PHP standalone).

2. Tray icon (X-to-tray when server running)
   Closing the dev panel hides both the form HWND and the TFMAppClass
   per-process proxy window that owns the FMX taskbar entry — the form's
   HWND alone is not the taskbar-visible one in FMX (took some iteration
   to discover). Tray menu: Open, Lock vault, Quit. Clipboard is force-
   cleared on minimize as extra safety. First-time minimize fires a
   balloon notification so the user knows the app is still running.

3. Auto-lock on Windows session lock (Win+L)
   wtsapi32.dll!WTSRegisterSessionNotification on a dedicated message-only
   window. On WM_WTSSESSION_CHANGE / WTS_SESSION_LOCK, the bridge calls
   ExecuteJavaScript('lockVault()'). Same path used by the tray "Lock vault"
   menu item.

Bridge architecture:
 - JS → Delphi via cmd:// URLs intercepted in OnBeforeNavigate
   (pattern lifted from DeskInsight Monaco). Currently exposes
   cmd://clipboard/copy?text=...&clear=... and cmd://clipboard/clear.
 - Delphi → JS via TTMSFNCWebBrowser.ExecuteJavaScript with guarded
   calls (typeof check) so the bridge degrades cleanly if app.js isn't
   loaded yet.

Files:
 - Source/PM.Bridge.pas (new) — TSecureClipboard + TPMBridge
 - UMainForm.pas/.fmx — bridge wiring, FormCloseQuery intercept, tray
   callbacks (BridgeTrayRestore / BridgeLockRequest / BridgeQuit)
 - js/app.js — Bridge object, 5 navigator.clipboard sites migrated to
   Bridge.copySecure with PHP-compatible fallback, Bridge.onTrayRestore
   handler that resets the auto-lock timer

.gitignore extended with Delphi build artifacts (*.dcu, Win32/, Win64/,
__history/, __recovery/, *.identcache, *.dsk, *.local, etc.) so source
checkouts stay clean.
2026-05-22 23:47:57 +01:00
Zaki 159e02ae81 Fix double toast on single delete: pass noToast to delEntry. Remove auto-dismiss timeout on undo toasts (visible until clicked). 2026-05-12 19:55:30 +01:00
Zaki 73818e4e2e Add undo to drag-drop trash. Fix toast undo button visibility (darker bg, border, max-width). 2026-05-12 19:46:01 +01:00
Zaki ff9802e685 Add undo button in toast for trash actions (single + batch) 2026-05-12 19:40:23 +01:00
Zaki 617b8a7efe Hide FABs when auth visible (locked). Trash FAB glow shadow when active. 2026-05-12 19:36:35 +01:00
Zaki eb15d9e849 Trash FAB: always transparent background, no shadow 2026-05-12 15:49:40 +01:00
Zaki 59d407558b Trash FAB: always shows 🗑️; active mode has transparent background, no shadow 2026-05-12 15:33:12 +01:00
Zaki d1a26fc0d6 Add vault-error.log to .gitignore 2026-05-12 15:15:10 +01:00
Zaki f8c684669d Remove accidentally committed vault-error.log 2026-05-12 15:14:47 +01:00
Zaki 5836bd168d Fix dblclick: clear selection, select entry, render, open edit. closeEdit calls render. Trash FAB: moved from toolbar to floating button at bottom-left (like add FAB). 2026-05-12 15:14:39 +01:00
Zaki d55be5f19e Fix entry card contrast (lighter card, more visible border). Fix dblclick: force-select entry before opening edit. 2026-05-12 14:20:46 +01:00
Zaki b51e9c3a73 Theme: neutral dark gray, card shadows, accent-rgb vars. Fix: arrows skip when modals open. Fix: detail view respects folder filter.
Dark theme: neutral dark grays (#0e1015 bg, #6b7280 accent). Light theme: white cards, better contrast. Cards now have subtle shadows for separation. All hardcoded rgba(59,130,246) replaced with rgba(var(--accent-rgb), ...). Arrow key handler skips when add/edit modal is open. Detail view now uses getFilteredEntries() instead of getFilteredEntries(true) to respect folder selection.
2026-05-12 13:51:41 +01:00
Zaki dfcbc3f568 Theme: neutral dark gray, higher card contrast. Detail view: folder filtering works. Modals: arrow nav blocked when modal open, Enter saves from anywhere inside modal. 2026-05-12 13:35:46 +01:00
Zaki 194c11ece2 Fix Shift+arrow range selection: track anchor (fixed) and focus (moving) separately
Previous approach always started from the lowest-indexed selected entry, causing the range to snap to anchor on arrow reversal. Now arrowFocus tracks the moving end; arrowAnchor stays fixed. Non-Shift arrow resets both to the new position.
2026-05-09 23:36:39 +01:00
Zaki 0a0e380b95 Fix shift+arrow anchor and detail view arrow navigation
Shift+arrow now uses arrowAnchor (set on first arrow press) instead of lastSelectedId (which was updated on each non-Shift move). Fixes 'only 2 entries' bug. Detail view: fixed inverted auth check for ArrowLeft/Right; general arrow handler now excludes detail view.
2026-05-09 23:32:36 +01:00
Zaki 3802f1fc23 Grid view: arrow up/down moves vertically by column count; left/right moves linearly 2026-05-09 23:23:30 +01:00
Zaki b0785fbe8d Arrow left/right navigate entries; Shift+arrow extends multi-selection 2026-05-09 23:16:17 +01:00
Zaki 72d7d1015a Arrow up/down to navigate entries, Enter to open selected for editing 2026-05-09 23:12:09 +01:00
Zaki 52a4242a52 Auto-focus: loginUsername on load, website in add/edit modals. Enter saves from anywhere inside modals. 2026-05-09 22:41:52 +01:00
Zaki 49e1ab4730 Mark resolved issues in security-issues.md 2026-05-09 22:29:09 +01:00
Zaki 69b17e4505 Fix password generator modulo bias with rejection sampling
Use single-byte rejection sampling: generate byte, reject if >= largest multiple of charset length, then modulo. Eliminates bias from c.charAt(arr[i] % c.length).
2026-05-09 22:28:54 +01:00
Zaki 46d7ca3694 Add CSP header and session rotation on login
Content-Security-Policy: default-src 'self'; restricts external resource loading. Session rotation: delete all existing sessions for a user on login, so re-logging invalidates any leaked tokens.
2026-05-09 22:24:08 +01:00
Zaki 4ddf2e9be6 Fix Enter in edit modal: switch from keypress (deprecated) to keydown 2026-05-09 22:20:09 +01:00
Zaki 6915ce518b Rate-limit /reauth endpoint: 5 attempts per 15min 2026-05-09 22:17:03 +01:00
Zaki ca7555a603 Fix Enter key in add modal: password field id is addPassword, not passwordInput 2026-05-09 22:14:46 +01:00
Zaki f4a542885a Enter key saves in add/edit modals from any field
Pressing Enter in addSite, addUsername, passwordInput calls addEntry(). Enter in editSite, editUsername, editPassword calls saveEdit().
2026-05-09 21:27:59 +01:00
Zaki f00bb2cdeb Add double-click on entry to open edit modal
Double-click any entry card/row (all views incl. detail) opens the edit modal. Excluded from trash view.
2026-05-09 21:08:51 +01:00
Zaki 70c22ce153 Change shortcuts: Alt+N for new entry, Alt+T for toggle trash
Ctrl+N and Ctrl+T cannot be intercepted by Chrome (browser-level shortcuts). Replaced with Alt+N and Alt+T which work reliably. Updated keyboard shortcuts help.
2026-05-09 21:03:32 +01:00
Zaki eb82bd416d Fix Ctrl+N/T: use e.key instead of e.code, remove duplicate guard
Switched from e.code (physical key position) to e.key (character value) which is more reliable across keyboard layouts and browsers. Also removed duplicate Ctrl guard line.
2026-05-09 19:44:44 +01:00
Zaki bfe20d29ec Fix Ctrl+N/T: use window capture phase to intercept before browser chrome
document-level keydown bubbling phase is too late for browser-level shortcuts Ctrl+N (new window) and Ctrl+T (new tab). Moved handlers to a window.addEventListener('keydown', ..., true) capture-phase handler that fires before the browser chrome acts. Removed redundant document-level copies.
2026-05-09 19:24:36 +01:00
Zaki 03c20fcb8c Fix Ctrl+N/T opening browser windows instead of app actions
Moved Ctrl+N and Ctrl+T handlers before the generic Ctrl guard with their own e.preventDefault() and early return, matching the pattern used for Ctrl+A. Removed them from the old else-if chain and combined preventDefault block.
2026-05-09 19:22:15 +01:00
Zaki 37c15ecad6 Fix Ctrl+A: use e.key instead of e.code, move before generic Ctrl guard
Ctrl+A was selecting page text instead of entries. Switched from e.code === 'KeyA' (layout-dependent) to e.key === 'a'. Moved handler before the generic Ctrl+key else-if chain and before the combined preventDefault block, with its own e.preventDefault() and early return. Handles both 'a' and 'A' key values.
2026-05-09 19:13:58 +01:00
Zaki e414b4f600 Fix Ctrl+A and add Delete key shortcut
Ctrl+A auth check was inverted (!hidden instead of hidden), preventing selection in vault. Added Delete key shortcut: moves selected entries to trash (or batch permanent delete in trash view). Added Del to keyboard shortcuts help.
2026-05-09 19:04:36 +01:00
Zaki f40024cc67 Fix: mousedown clears selectedIds before batch callback runs
Document mousedown handler was clearing selectedIds when clicking 'Yes' (button element). Since mousedown fires before click, selectedIds was empty by the time the async callback read it, causing no-op deletes but still showing the toast. Added .batch-confirm-overlay to the mousedown exclusion list so clicking the confirm dialog won't trigger clearSelection().
2026-05-09 18:46:27 +01:00
Zaki 02e5868d66 Fix batch confirm: modal overlay + positioned beside button
Replace showCenterConfirm with showBatchConfirm(btn,message,callback) that creates a transparent modal overlay (z-index 9999) to block background clicks, positions the confirm dialog beside the trigger button. Updated all callers (batchDelete, batchPermanentDelete, permanentDelete, emptyTrash) to pass the clicked button. Added CSS for batch-confirm-overlay backdrop.
2026-05-09 18:37:57 +01:00
Zaki 131bb91cd2 Replace standard confirm() with custom centered confirm dialog
Add showCenterConfirm() function for dialogs without button anchor. Replaced all standard confirm() calls in batchDelete, batchPermanentDelete, permanentDelete, emptyTrash. Batch permanent delete shows single custom confirm with entry count, no nested dialogs. permanentDelete() accepts silent param to suppress UI for batch operations. Order cleanup added to permanentDelete.
2026-05-09 18:20:06 +01:00
Zaki 7e623067b0 Fix: batch toast spam on trash drag, restore icon, stale ref, reorder safety
Trash drop handler now uses noToast + single message. Restore button icon changed to ♻️. Removed stale .view-toggle reference in click-outside handler. Added safety check in reorder drop handler to prevent entries being lost from order array.
2026-05-09 17:55:52 +01:00
Zaki 0b3f886337 Fix batch toast spam and add Ctrl+A select all
Batch delete/restore now shows single toast with count instead of one per entry. delEntry() and restoreEntry() accept noToast param. Added Ctrl+A to select all visible entries. Updated keyboard shortcuts help.
2026-05-09 17:44:12 +01:00
Zaki d50aea6845 Add 3 new views (Card, Grouped, Detail) and view dropdown
Replace view toggle buttons with dropdown menu containing all 7 views. Card view: 2-column grid with bigger cards. Grouped view: entries grouped by folder with sticky headers. Detail view: single entry at a time, large text, prev/next navigation. Arrow key navigation for detail view.
2026-05-09 16:51:38 +01:00