258 lines
9.6 KiB
Python
258 lines
9.6 KiB
Python
"""
|
|
Server-side persistence for the PWA's small client state — the Settings panel
|
|
config (theme, currency, subscription, prompt shortcuts) and the notification
|
|
feed's seen/new bookkeeping — that used to live in the browser's ``localStorage``.
|
|
|
|
Moving it into a file (``/data/ui-state.json``) makes the config follow the user
|
|
across browsers and devices instead of being trapped per-browser, and survives a
|
|
localStorage clear. The store is a dumb key→string map: each key is a Zustand
|
|
``persist`` store name (``ai-agent-settings`` / ``ai-agent-store``) and the value
|
|
is that store's already-serialized JSON blob — the backend never inspects it, it
|
|
just holds the opaque string the frontend hands it.
|
|
|
|
Single JSON file, whole-map rewrite on every set (atomic via a temp file + rename),
|
|
mirroring ``meta.py``. The map is tiny, so this is cheap.
|
|
|
|
Before the first write of each day the current file is copied to
|
|
``ui-state.json.bak-YYYY-MM-DD`` (the last ``BACKUP_DAYS`` kept): a client that
|
|
ever persists its defaults over the real config — as happened once to a whole
|
|
prompt-shortcut set — then costs a restore, not the config.
|
|
"""
|
|
|
|
import datetime
|
|
import json
|
|
import pathlib
|
|
import re
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
|
|
# Keys are Zustand persist store names — restrict to a safe, fixed shape so a
|
|
# bogus key can never escape the single JSON blob or collide with anything else.
|
|
_KEY_RE = re.compile(r"^[A-Za-z0-9_.-]{1,128}$")
|
|
|
|
BACKUP_DAYS = 14
|
|
_LEAKED_SETTINGS_THRESHOLD = 10 * 1024
|
|
_NOTIF_KNOWN_CAP = 500
|
|
|
|
_SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS ui_state (
|
|
key TEXT PRIMARY KEY,
|
|
value TEXT NOT NULL,
|
|
updated_at REAL NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS _meta (
|
|
key TEXT PRIMARY KEY,
|
|
value TEXT
|
|
);
|
|
"""
|
|
|
|
|
|
def valid_key(key: str) -> bool:
|
|
return bool(_KEY_RE.match(key))
|
|
|
|
|
|
def _notif_at(nid) -> str | None:
|
|
if not isinstance(nid, str):
|
|
return None
|
|
parts = nid.split("#")
|
|
return parts[1] if len(parts) >= 2 and parts[1] else None
|
|
|
|
|
|
def _scrub_guest_settings(raw: str) -> str | None:
|
|
"""Drop leaked owner customIcons/tagMeta from a guest settings blob when
|
|
their combined size exceeds 10 KB. Returns the cleaned JSON string or None."""
|
|
try:
|
|
blob = json.loads(raw)
|
|
except (ValueError, TypeError):
|
|
return None
|
|
if not isinstance(blob, dict) or not isinstance(blob.get("state"), dict):
|
|
return None
|
|
st = blob["state"]
|
|
if "customIcons" not in st and "tagMeta" not in st:
|
|
return None
|
|
leaked = 0
|
|
if "customIcons" in st:
|
|
leaked += len(json.dumps(st["customIcons"]).encode("utf-8"))
|
|
if "tagMeta" in st:
|
|
leaked += len(json.dumps(st["tagMeta"]).encode("utf-8"))
|
|
if leaked <= _LEAKED_SETTINGS_THRESHOLD:
|
|
return None
|
|
st.pop("customIcons", None)
|
|
st.pop("tagMeta", None)
|
|
return json.dumps(blob)
|
|
|
|
|
|
def _scrub_guest_store(raw: str) -> str | None:
|
|
"""Prune notifKnown / notifNew / notifUnread older than notifBaseline (and
|
|
cap notifKnown to the most recent 500 IDs when notifBaseline is present).
|
|
Returns the cleaned JSON string or None if unchanged."""
|
|
try:
|
|
blob = json.loads(raw)
|
|
except (ValueError, TypeError):
|
|
return None
|
|
if not isinstance(blob, dict) or not isinstance(blob.get("state"), dict):
|
|
return None
|
|
st = blob["state"]
|
|
baseline = st.get("notifBaseline")
|
|
if not isinstance(baseline, str) or not baseline:
|
|
return None
|
|
changed = False
|
|
for field in ("notifKnown", "notifNew", "notifUnread"):
|
|
arr = st.get(field)
|
|
if not isinstance(arr, list) or not arr:
|
|
continue
|
|
filtered = [x for x in arr if not ((ts := _notif_at(x)) is not None and ts < baseline)]
|
|
if field == "notifKnown" and len(filtered) > _NOTIF_KNOWN_CAP:
|
|
filtered = filtered[-_NOTIF_KNOWN_CAP:]
|
|
if len(filtered) != len(arr):
|
|
st[field] = filtered
|
|
changed = True
|
|
return json.dumps(blob) if changed else None
|
|
|
|
|
|
class UiStateStore:
|
|
def __init__(self, path: str):
|
|
self.path = pathlib.Path(path)
|
|
self.db_path = self.path.with_suffix(".db")
|
|
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
self._lock = threading.Lock()
|
|
self._data: dict[str, str] = {}
|
|
self._last_backup_day: str | None = None
|
|
self._db = sqlite3.connect(str(self.db_path), check_same_thread=False)
|
|
self._db.execute("PRAGMA journal_mode=WAL")
|
|
self._db.execute("PRAGMA synchronous=NORMAL")
|
|
self._db.execute("PRAGMA busy_timeout=5000")
|
|
self._db.execute("PRAGMA journal_size_limit=16777216")
|
|
self._db.executescript(_SCHEMA)
|
|
self._db.commit()
|
|
self._load()
|
|
|
|
def _load(self) -> None:
|
|
migrated = self._db.execute(
|
|
"SELECT value FROM _meta WHERE key='migrated_mtime'"
|
|
).fetchone()
|
|
count = self._db.execute("SELECT COUNT(*) FROM ui_state").fetchone()[0]
|
|
if migrated is None and count == 0 and self.path.exists():
|
|
try:
|
|
st_mtime = self.path.stat().st_mtime
|
|
data = json.loads(self.path.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
data = {}
|
|
st_mtime = None
|
|
if isinstance(data, dict):
|
|
now = time.time()
|
|
rows = [(k, v, now) for k, v in data.items() if isinstance(v, str)]
|
|
if rows:
|
|
self._db.executemany(
|
|
"INSERT OR REPLACE INTO ui_state (key, value, updated_at) VALUES (?,?,?)",
|
|
rows,
|
|
)
|
|
if st_mtime is not None:
|
|
self._db.execute(
|
|
"INSERT INTO _meta (key, value) VALUES ('migrated_mtime', ?) "
|
|
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
|
|
(str(st_mtime),),
|
|
)
|
|
self._db.commit()
|
|
|
|
self._data = {
|
|
k: v for k, v in self._db.execute("SELECT key, value FROM ui_state").fetchall()
|
|
if isinstance(v, str)
|
|
}
|
|
self._scrub_once()
|
|
|
|
def _scrub_once(self) -> None:
|
|
done = self._db.execute("SELECT value FROM _meta WHERE key='scrub_v1'").fetchone()
|
|
if done is not None:
|
|
return
|
|
now = time.time()
|
|
updates: list[tuple[str, float, str]] = []
|
|
for key, raw in list(self._data.items()):
|
|
cleaned: str | None = None
|
|
if key.startswith("u.") and key.endswith(".ai-agent-settings"):
|
|
cleaned = _scrub_guest_settings(raw)
|
|
elif key.startswith("u.") and key.endswith(".ai-agent-store"):
|
|
cleaned = _scrub_guest_store(raw)
|
|
if cleaned is not None and cleaned != raw:
|
|
self._data[key] = cleaned
|
|
updates.append((cleaned, now, key))
|
|
if updates:
|
|
self._db.executemany(
|
|
"UPDATE ui_state SET value=?, updated_at=? WHERE key=?",
|
|
updates,
|
|
)
|
|
self._db.execute(
|
|
"INSERT INTO _meta (key, value) VALUES ('scrub_v1', '1') "
|
|
"ON CONFLICT(key) DO UPDATE SET value=excluded.value"
|
|
)
|
|
self._db.commit()
|
|
|
|
def get(self, key: str) -> str | None:
|
|
with self._lock:
|
|
return self._data.get(key)
|
|
|
|
def set(self, key: str, value: str) -> None:
|
|
with self._lock:
|
|
if self._data.get(key) == value:
|
|
return
|
|
self._backup()
|
|
self._db.execute(
|
|
"INSERT INTO ui_state (key, value, updated_at) VALUES (?,?,?) "
|
|
"ON CONFLICT(key) DO UPDATE SET value=excluded.value, "
|
|
"updated_at=excluded.updated_at",
|
|
(key, value, time.time()),
|
|
)
|
|
self._db.commit()
|
|
self._data[key] = value
|
|
|
|
def usage(self, prefix: str, but: str = "") -> tuple[int, int]:
|
|
"""(bytes, keys) held under ``prefix``, the key ``but`` left out —
|
|
what one guest's namespace weighs before a write replaces ``but``."""
|
|
with self._lock:
|
|
mine = [v for k, v in self._data.items() if k.startswith(prefix) and k != but]
|
|
return sum(len(v.encode("utf-8")) for v in mine), len(mine)
|
|
|
|
def delete(self, key: str) -> None:
|
|
with self._lock:
|
|
if key in self._data:
|
|
self._backup()
|
|
self._db.execute("DELETE FROM ui_state WHERE key=?", (key,))
|
|
self._db.commit()
|
|
del self._data[key]
|
|
|
|
def delete_prefix(self, prefix: str) -> int:
|
|
with self._lock:
|
|
gone = [k for k in self._data if k.startswith(prefix)]
|
|
if not gone:
|
|
return 0
|
|
self._backup()
|
|
self._db.execute(
|
|
f"DELETE FROM ui_state WHERE key IN ({','.join('?' * len(gone))})",
|
|
gone,
|
|
)
|
|
self._db.commit()
|
|
for k in gone:
|
|
del self._data[k]
|
|
return len(gone)
|
|
|
|
def _backup(self) -> None:
|
|
"""Daily snapshot of the DB as it was before today's first write (lock held)."""
|
|
today = f"{datetime.date.today():%Y-%m-%d}"
|
|
if self._last_backup_day == today:
|
|
return
|
|
self._last_backup_day = today
|
|
bak = self.db_path.with_name(f"{self.db_path.name}.bak-{today}")
|
|
if bak.exists() or not self._data:
|
|
return
|
|
try:
|
|
dst = sqlite3.connect(str(bak))
|
|
try:
|
|
self._db.backup(dst)
|
|
finally:
|
|
dst.close()
|
|
for old in sorted(self.db_path.parent.glob(f"{self.db_path.name}.bak-*"))[:-BACKUP_DAYS]:
|
|
old.unlink(missing_ok=True)
|
|
except (OSError, sqlite3.Error):
|
|
pass
|