Skip to content
42 changes: 42 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,47 @@
# backend HASHOUT_LOG · formDAM
current: v1.27.2 · 2026-10-22
### app/routers/trash.py keychain_enable · wrong passkeys sent to save the passkey on the device count toward the same limit
- refers-to: routers/trash.py keychain_enable; vault.py attempt_guard, attempt_failed, attempt_cleared; tests/test_f1_guard.py (one new test)
- kind: fix
- logged: after v1.32.4 · 2026-11-28

Saving the passkey to the device store checks it against the vault passkey first, so it answered right or wrong like vault unlock did, but without the limit on wrong passkeys. It now shares the vault's count: after 10 wrong passkeys within 5 minutes on either route, both answer 429, and a right passkey clears the count.
### app/routers/library.py _disk_packet, app/services/xmpsvc.py merge_packet · a sidecar that is not UTF-8 is left alone, and one file's prefixes do not carry into the next
- refers-to: routers/library.py _disk_packet; services/xmpsvc.py merge_packet; tests/test_p1_xmp.py (two new tests)
- kind: fix
- logged: after v1.32.4 · 2026-11-28

The Disk browser read another tool's sidecar with undecodable bytes replaced, so merging a rating into a sidecar saved in another encoding would have rewritten its text with replacement characters. It now reads strictly and leaves such a sidecar as it is, not counted as written. merge_packet registers a sidecar's own namespace prefixes so they serialize under their own names; those registrations are process wide, so a sidecar that used an older prefix for a known namespace (xap for xmp) changed the prefix of every later merge. The known prefixes are registered again after each merge.
### app/services/native_picker.py _mac, _windows · the starting folder reaches the system dialog as data, never inside the script text
- refers-to: services/native_picker.py SEED_ENV (new), _run, _mac, _windows; tests/test_native_picker.py (new)
- kind: fix
- logged: after v1.32.4 · 2026-11-28

The Windows picker put the starting folder inside a single-quoted PowerShell string and turned away only the ASCII apostrophe, but PowerShell also reads the curly single quotes as quotes, so a folder name could end the string. The macOS picker did the same with a double-quoted AppleScript string. Windows now reads the folder from the `FORMDAM_PICK_INITIAL` environment variable of the PowerShell child (`$env:FORMDAM_PICK_INITIAL`). macOS passes the absolute folder as the script's first argument (`on run argv`, `item 1 of argv`); `system attribute` was tried and rejected because it decodes the variable as Mac Roman and mangled a name with a curly quote. Folders whose names held a quote are now offered as the starting folder too, where before they were dropped. Linux already passed it as an argument. Checked here: the macOS script compiles with osacompile and argv kept a name with curly and straight quotes unchanged. Not run on Windows.
### app/services/outputsvc.py _free_target · export with sidecars picks a name whose sidecar is free too
- refers-to: services/outputsvc.py _free_target (new), export_one; tests/test_p1_xmp.py (one new test)
- kind: fix
- logged: after v1.32.4 · 2026-11-28

Only the exported image's name was made unique, so `<stem>.xmp` could replace a sidecar already in the destination folder (exporting beside the originals), and the two halves of a RAW and JPEG pair wrote the same sidecar. With the sidecar option on, a candidate name is used only when neither the image nor its `.xmp` exists or was taken earlier in the same export; the next free `-1`, `-2` name is used otherwise, and both names are recorded as taken. With the option off, naming is as before.
### app/vaultcrypt.py purge, _edit_files_in_use · deleting an item for good keeps an edit file another item points at
- refers-to: vaultcrypt.py purge, _edit_files_in_use (new); services/syncsvc.py _fetch_edit (unchanged); tests/test_trash.py (one new test)
- kind: fix
- logged: after v1.32.4 · 2026-11-28

Edit files are named `<id>-<stamp>[-n].ext` after the id on the device that made them, and sync copies them under that same name, so on another device the name can start with the id of an unrelated item. purge removed every `edits/<id>-*` file and could take another photo's edited version with it. It now skips any file named in another item's edit_json `external.file`. The files are not renamed on arrival, because the name travels inside the synced edit record.
### app/routers/trash.py vault_setup, vault_unlock; app/routers/albums.py unlock_album; app/vault.py attempt_guard · the vault passkey is set only in the window, and wrong passkeys are limited
- refers-to: routers/trash.py vault_setup, vault_unlock; routers/albums.py unlock_album; vault.py ATTEMPT_LIMIT, ATTEMPT_WINDOW, attempt_guard, attempt_failed, attempt_cleared (new); tests/test_f1_guard.py (two new tests)
- kind: fix
- logged: after v1.32.4 · 2026-11-28

Choosing the vault passkey decides who can open Hidden and Recently Deleted, so it is now a window or desktop shell action, the same rule device unlock already had; an automation token gets 403. Unlocking with a passkey still works for automation. After 10 wrong passkeys within 5 minutes, for the vault or for one album with its own passkey, the engine answers 429 until the oldest failure is 5 minutes old; a right passkey clears the count. The count lives in the engine process and starts empty at each launch.
### app/routers/library.py disk_meta, app/services/xmpsvc.py merge_packet · a rating from the Disk browser keeps the rest of a sidecar written by another tool
- refers-to: routers/library.py _disk_packet (new), disk_meta; services/xmpsvc.py owned_packet, merge_packet (new), write_sidecar; tests/test_p1_xmp.py (three new tests)
- kind: fix
- logged: after v1.32.4 · 2026-11-28

Setting a rating, label or keyword on a file in the Disk browser rebuilt its sidecar from the few fields formDAM reads, so develop settings, history and anything else another tool kept there were lost. The Disk browser now treats a sidecar the way write_sidecar does: one that formDAM wrote (x:xmptk="FormDAM") is rebuilt as before; one from another tool is parsed as XML and only xmp:Rating, xmp:Label, xmp:MetadataDate, dc:subject and lr:hierarchicalSubject on its first rdf:Description are changed, every other attribute and element is kept, and its namespace prefixes are registered so they serialize under their own names. A sidecar that does not parse is left as it is and the file is not counted as written. A file with no sidecar gets a new formDAM packet as before.
### ../setup/build_windows_app.bat WINDOWED · the Windows engine is frozen with no console of its own
- refers-to: setup/build_windows_app.bat WINDOWED, FORMDAM_ENGINE_WINDOWED; desktop_entry.py the stream guard at the top, _Tee, _open_log; src-tauri/src/main.rs backend_command, forward_lines, read_port; tests/test_entry_streams.py (three new tests)
- kind: decision
Expand Down
6 changes: 5 additions & 1 deletion backend/app/routers/albums.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from pydantic import BaseModel, Field

from ..db import ex, media_dict, now, q, q1
from ..vault import check_token, hash_passkey, issue_token, vault_hash, verify_passkey
from ..vault import attempt_cleared, attempt_failed, attempt_guard, check_token, hash_passkey, issue_token, vault_hash, verify_passkey
from .guard import token_of

router = APIRouter()
Expand Down Expand Up @@ -94,8 +94,12 @@ def unlock_album(album_id: int, body: UnlockIn):
if not album["is_private"]:
raise HTTPException(422, detail="Album is not private")
stored = album["passkey_hash"] or vault_hash()
key = f"album:{album_id}" if album["passkey_hash"] else "vault"
attempt_guard(key)
if stored is None or not verify_passkey(body.passkey, stored):
attempt_failed(key)
raise HTTPException(401, detail="Wrong passkey")
attempt_cleared(key)
from .. import vaultcrypt
if album["passkey_hash"]:
opened = vaultcrypt.unlock_album(album_id, body.passkey)
Expand Down
24 changes: 22 additions & 2 deletions backend/app/routers/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,23 @@ def _sidecar_record(path: str) -> Dict[str, Any]:
return {}


def _disk_packet(path: str, rec: Dict[str, Any], body: DiskMetaIn) -> Optional[tuple]:
from ..services import xmpsvc

side = xmpsvc.find_sidecar(path)
if side is None:
return xmpsvc.sidecar_for(path), xmpsvc.build_xmp(rec)
try:
with open(side, "r", encoding="utf-8") as fh:
current = fh.read()
except (OSError, UnicodeDecodeError):
return None
if xmpsvc.owned_packet(current):
return side, xmpsvc.build_xmp(rec)
merged = xmpsvc.merge_packet(current, rating=body.rating, label=body.label, keywords=body.keywords)
return (side, merged) if merged is not None else None


@router.post("/disk/meta")
def disk_meta(body: DiskMetaIn):
from ..services import xmpsvc
Expand All @@ -296,10 +313,13 @@ def disk_meta(body: DiskMetaIn):
rec["label"] = body.label
if body.keywords:
rec["keywords"] = sorted(set(rec.get("keywords") or []) | set(body.keywords))
side = xmpsvc.find_sidecar(path) or xmpsvc.sidecar_for(path)
packet = _disk_packet(path, rec, body)
if packet is None:
continue
side, text = packet
tmp = side + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
fh.write(xmpsvc.build_xmp(rec))
fh.write(text)
os.replace(tmp, side)
hit = q1("SELECT id FROM media WHERE rel_path=?", (path,))
if hit:
Expand Down
12 changes: 10 additions & 2 deletions backend/app/routers/trash.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from ..db import ex, media_dict, q, q1
from ..security import shell_allowed, window_allowed
from ..services import libraryfs
from ..vault import issue_token, set_vault, vault_hash, verify_passkey
from ..vault import attempt_cleared, attempt_failed, attempt_guard, issue_token, set_vault, vault_hash, verify_passkey
from .guard import require_vault

router = APIRouter()
Expand All @@ -26,7 +26,9 @@ def vault_status():


@router.post("/vault/setup")
def vault_setup(body: PasskeyIn):
def vault_setup(body: PasskeyIn, request: Request):
if not (window_allowed(request) or shell_allowed(request)):
raise HTTPException(403, detail="The vault passkey can only be set in the formDAM window")
if vault_hash() is not None:
raise HTTPException(409, detail="Vault passkey already set")
set_vault(body.passkey)
Expand All @@ -40,8 +42,11 @@ def vault_unlock(body: PasskeyIn):
stored = vault_hash()
if stored is None:
raise HTTPException(409, detail="Vault passkey not set yet")
attempt_guard("vault")
if not verify_passkey(body.passkey, stored):
attempt_failed("vault")
raise HTTPException(401, detail="Wrong passkey")
attempt_cleared("vault")
from .. import vaultcrypt
if not vaultcrypt.unlock_vault(body.passkey):
raise HTTPException(500, detail="The vault key could not be opened with this passkey")
Expand Down Expand Up @@ -150,8 +155,11 @@ def device_unlock_labels():
@router.post("/vault/keychain/enable")
def keychain_enable(body: PasskeyIn):
stored = vault_hash()
attempt_guard("vault")
if stored is None or not verify_passkey(body.passkey, stored):
attempt_failed("vault")
raise HTTPException(401, detail="Wrong passkey")
attempt_cleared("vault")
entry = _ctrl_roundtrip("KCSTORE", passkey=body.passkey)
if not entry.get("ok"):
raise HTTPException(500, detail=f"The shell could not save the passkey to {device_labels()['store']}")
Expand Down
26 changes: 18 additions & 8 deletions backend/app/services/native_picker.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,27 @@ class PickerUnavailable(Exception):
pass


def _run(cmd: List[str]) -> subprocess.CompletedProcess:
return subprocess.run(cmd, capture_output=True, text=True)
SEED_ENV = "FORMDAM_PICK_INITIAL"


def _run(cmd: List[str], seed: Optional[str] = None) -> subprocess.CompletedProcess:
env = None
if seed is not None:
env = {**os.environ, SEED_ENV: seed}
return subprocess.run(cmd, capture_output=True, text=True, env=env)


def _mac(initial: Optional[str]) -> Optional[str]:
prompt = "Choose a folder to import into formDAM"
script = f'POSIX path of (choose folder with prompt "{prompt}" with showing package contents)'
if initial and os.path.isdir(initial) and '"' not in initial:
cmd = ["osascript", "-e", script]
if initial and os.path.isdir(initial):
script = (
f'POSIX path of (choose folder with prompt "{prompt}" '
f'default location POSIX file "{initial}" with showing package contents)'
'default location POSIX file (item 1 of argv) with showing package contents)'
)
proc = _run(["osascript", "-e", script])
cmd = ["osascript", "-e", "on run argv", "-e", script, "-e", "end run", os.path.abspath(initial)]
proc = _run(cmd)
if proc.returncode != 0:
if "canceled" in proc.stderr.lower() or "cancelled" in proc.stderr.lower():
return None
Expand All @@ -38,8 +46,10 @@ def _mac(initial: Optional[str]) -> Optional[str]:

def _windows(initial: Optional[str]) -> Optional[str]:
seed = ""
if initial and os.path.isdir(initial) and "'" not in initial:
seed = f"$dialog.SelectedPath = '{initial}';"
value = None
if initial and os.path.isdir(initial):
value = initial
seed = f"$dialog.SelectedPath = $env:{SEED_ENV};"
script = (
"Add-Type -AssemblyName System.Windows.Forms;"
"$dialog = New-Object System.Windows.Forms.FolderBrowserDialog;"
Expand All @@ -49,7 +59,7 @@ def _windows(initial: Optional[str]) -> Optional[str]:
+ "if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)"
+ " { Write-Output $dialog.SelectedPath }"
)
proc = _run(["powershell", "-NoProfile", "-STA", "-Command", script])
proc = _run(["powershell", "-NoProfile", "-STA", "-Command", script], value)
if proc.returncode != 0:
raise PickerUnavailable(f"The Windows folder dialog could not open: {proc.stderr.strip() or 'unknown error'}")
return proc.stdout.strip() or None
Expand Down
22 changes: 20 additions & 2 deletions backend/app/services/outputsvc.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,24 @@ def _copy_stripped(src: Any, target: str, row, opts: Dict[str, Any]) -> None:
raise ExportError(f"{row['name']}: location could not be removed from this original")


def _free_target(path: str, taken: set, sidecar: bool) -> str:
base, ext = os.path.splitext(path)
cand, i = path, 1
while True:
side = os.path.splitext(cand)[0] + ".xmp"
busy = os.path.exists(cand) or cand in taken
if sidecar:
busy = busy or os.path.exists(side) or side in taken
if not busy:
break
cand = f"{base}-{i}{ext}"
i += 1
taken.add(cand)
if sidecar:
taken.add(os.path.splitext(cand)[0] + ".xmp")
return cand


def export_one(row, dest: str, seq: int, opts: Dict[str, Any], taken: set) -> Optional[str]:
from ..routers.render import source_of

Expand All @@ -139,7 +157,7 @@ def export_one(row, dest: str, seq: int, opts: Dict[str, Any], taken: set) -> Op
base = renamesvc.safe(renamesvc.expand(opts.get("naming") or "{name}", dict(row), seq, opts.get("custom", "")))
if opts.get("original") or row["kind"] != "image":
ext = os.path.splitext(row["name"])[1]
target = filesvc._unique(os.path.join(folder, base + ext), taken)
target = _free_target(os.path.join(folder, base + ext), taken, bool(opts.get("sidecar")))
if not opts.get("location", True) or row["location_hidden"] or opts.get("metadata") == "none":
_copy_stripped(src, target, row, opts)
elif isinstance(src, (bytes, bytearray)):
Expand All @@ -162,7 +180,7 @@ def export_one(row, dest: str, seq: int, opts: Dict[str, Any], taken: set) -> Op
img = img.resize(size, Image.Resampling.LANCZOS)
if fmt in ("JPEG", "HEIF") or img.mode not in ("RGB", "RGBA"):
img = img.convert("RGB")
target = filesvc._unique(os.path.join(folder, base + ext), taken)
target = _free_target(os.path.join(folder, base + ext), taken, bool(opts.get("sidecar")))
quality = int(opts.get("quality") or 90)
kwargs: Dict[str, Any] = {}
exif = _exif_bytes(src, row, opts)
Expand Down
71 changes: 70 additions & 1 deletion backend/app/services/xmpsvc.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,75 @@ def parse_xmp(text: str) -> Dict[str, Any]:
return out


def owned_packet(text: str) -> bool:
return 'x:xmptk="FormDAM"' in text[:65536]


def _read_packet(text: str):
import io

prefixes: Dict[str, str] = {}
try:
events = ET.iterparse(io.StringIO(text), events=("start-ns",))
for _event, (prefix, uri) in events:
prefixes.setdefault(prefix, uri)
root = events.root
except ET.ParseError:
return None
for prefix, uri in prefixes.items():
if prefix and prefix not in NS:
try:
ET.register_namespace(prefix, uri)
except ValueError:
pass
return root


def _set_simple(desc, prefix: str, name: str, value: Optional[str]) -> None:
for child in [c for c in desc if c.tag == _q(prefix, name)]:
desc.remove(child)
if value is None:
desc.attrib.pop(_q(prefix, name), None)
else:
desc.set(_q(prefix, name), value)


def _set_bag(desc, prefix: str, name: str, items: List[str]) -> None:
for child in [c for c in desc if c.tag == _q(prefix, name)]:
desc.remove(child)
desc.attrib.pop(_q(prefix, name), None)
el = ET.SubElement(desc, _q(prefix, name))
bag = ET.SubElement(el, _q("rdf", "Bag"))
for item in items:
ET.SubElement(bag, _q("rdf", "li")).text = item


def merge_packet(text: str, rating: Optional[int] = None, label: Optional[str] = None,
keywords: Optional[List[str]] = None) -> Optional[str]:
root = _read_packet(text)
if root is None:
return None
desc = next(root.iter(_q("rdf", "Description")), None)
if desc is None:
return None
if rating is not None:
_set_simple(desc, "xmp", "Rating", str(int(rating)))
if label is not None:
_set_simple(desc, "xmp", "Label", str(label).title() if label else None)
if keywords:
current = parse_xmp(text).get("keywords") or []
merged = sorted(set(current) | set(keywords))
_set_bag(desc, "dc", "subject", sorted({k.split("|")[-1] for k in merged}))
_set_bag(desc, "lr", "hierarchicalSubject", merged)
_set_simple(desc, "xmp", "MetadataDate", time.strftime("%Y-%m-%dT%H:%M:%S"))
try:
body = ET.tostring(root, encoding="unicode")
finally:
for prefix, uri in NS.items():
ET.register_namespace(prefix, uri)
return '<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?>\n' + body + '\n<?xpacket end="w"?>\n'


def sidecar_for(path: str) -> str:
return os.path.splitext(path)[0] + ".xmp"

Expand Down Expand Up @@ -326,7 +395,7 @@ def write_sidecar(media_id: int) -> Optional[str]:
head = fh.read(65536)
except OSError:
return None
if 'x:xmptk="FormDAM"' not in head:
if not owned_packet(head):
return None
tmp = side + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
Expand Down
27 changes: 26 additions & 1 deletion backend/app/vault.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@
import hmac
import os
import time
from typing import Optional
from typing import Dict, List, Optional

from fastapi import HTTPException

from .db import setting_get, setting_set

TOKEN_TTL = 30 * 60
_SECRET = os.urandom(32)
ATTEMPT_LIMIT = 10
ATTEMPT_WINDOW = 5 * 60
_FAILURES: Dict[str, List[float]] = {}


def _secret() -> bytes:
Expand Down Expand Up @@ -65,3 +70,23 @@ def vault_hash() -> Optional[str]:

def set_vault(passkey: str) -> None:
setting_set("vault_passkey", hash_passkey(passkey))


def _recent(key: str) -> List[float]:
cutoff = time.monotonic() - ATTEMPT_WINDOW
return [t for t in _FAILURES.get(key, []) if t > cutoff]


def attempt_guard(key: str) -> None:
recent = _recent(key)
_FAILURES[key] = recent
if len(recent) >= ATTEMPT_LIMIT:
raise HTTPException(429, detail="Too many wrong passkeys. Wait a few minutes and try again.")


def attempt_failed(key: str) -> None:
_FAILURES[key] = [*_recent(key), time.monotonic()]


def attempt_cleared(key: str) -> None:
_FAILURES.pop(key, None)
Loading
Loading