Add custom field support

This commit is contained in:
thePR0M3TH3AN
2025-07-04 19:01:47 -04:00
parent 2c3f07f30b
commit d2face4c99
5 changed files with 86 additions and 2 deletions

View File

@@ -112,6 +112,7 @@ class EntryManager:
url: Optional[str] = None, url: Optional[str] = None,
blacklisted: bool = False, blacklisted: bool = False,
notes: str = "", notes: str = "",
custom_fields: List[Dict[str, Any]] | None = None,
) -> int: ) -> int:
""" """
Adds a new entry to the encrypted JSON index file. Adds a new entry to the encrypted JSON index file.
@@ -138,6 +139,7 @@ class EntryManager:
"type": EntryType.PASSWORD.value, "type": EntryType.PASSWORD.value,
"kind": EntryType.PASSWORD.value, "kind": EntryType.PASSWORD.value,
"notes": notes, "notes": notes,
"custom_fields": custom_fields or [],
} }
logger.debug(f"Added entry at index {index}: {data['entries'][str(index)]}") logger.debug(f"Added entry at index {index}: {data['entries'][str(index)]}")
@@ -414,6 +416,8 @@ class EntryManager:
entry = data.get("entries", {}).get(str(index)) entry = data.get("entries", {}).get(str(index))
if entry: if entry:
if entry.get("type", entry.get("kind")) == EntryType.PASSWORD.value:
entry.setdefault("custom_fields", [])
logger.debug(f"Retrieved entry at index {index}: {entry}") logger.debug(f"Retrieved entry at index {index}: {entry}")
return entry return entry
else: else:
@@ -441,6 +445,7 @@ class EntryManager:
label: Optional[str] = None, label: Optional[str] = None,
period: Optional[int] = None, period: Optional[int] = None,
digits: Optional[int] = None, digits: Optional[int] = None,
custom_fields: List[Dict[str, Any]] | None = None,
) -> None: ) -> None:
""" """
Modifies an existing entry based on the provided index and new values. Modifies an existing entry based on the provided index and new values.
@@ -500,6 +505,12 @@ class EntryManager:
entry["notes"] = notes entry["notes"] = notes
logger.debug(f"Updated notes for index {index}.") logger.debug(f"Updated notes for index {index}.")
if custom_fields is not None:
entry["custom_fields"] = custom_fields
logger.debug(
f"Updated custom fields for index {index}: {custom_fields}"
)
data["entries"][str(index)] = entry data["entries"][str(index)] = entry
logger.debug(f"Modified entry at index {index}: {entry}") logger.debug(f"Modified entry at index {index}: {entry}")
@@ -629,11 +640,18 @@ class EntryManager:
username = entry.get("username", "") username = entry.get("username", "")
url = entry.get("url", "") url = entry.get("url", "")
notes = entry.get("notes", "") notes = entry.get("notes", "")
custom_fields = entry.get("custom_fields", [])
custom_match = any(
query_lower in str(cf.get("label", "")).lower()
or query_lower in str(cf.get("value", "")).lower()
for cf in custom_fields
)
if ( if (
query_lower in website.lower() query_lower in website.lower()
or query_lower in username.lower() or query_lower in username.lower()
or query_lower in url.lower() or query_lower in url.lower()
or query_lower in notes.lower() or query_lower in notes.lower()
or custom_match
): ):
results.append( results.append(
( (

View File

@@ -867,6 +867,18 @@ class PasswordManager:
url = input("Enter the URL (optional): ").strip() url = input("Enter the URL (optional): ").strip()
notes = input("Enter notes (optional): ").strip() notes = input("Enter notes (optional): ").strip()
custom_fields: list[dict[str, object]] = []
while True:
add_field = input("Add custom field? (y/N): ").strip().lower()
if add_field != "y":
break
label = input(" Field label: ").strip()
value = input(" Field value: ").strip()
hidden = input(" Hidden field? (y/N): ").strip().lower() == "y"
custom_fields.append(
{"label": label, "value": value, "is_hidden": hidden}
)
length_input = input( length_input = input(
f"Enter desired password length (default {DEFAULT_PASSWORD_LENGTH}): " f"Enter desired password length (default {DEFAULT_PASSWORD_LENGTH}): "
).strip() ).strip()
@@ -893,6 +905,7 @@ class PasswordManager:
url, url,
blacklisted=False, blacklisted=False,
notes=notes, notes=notes,
custom_fields=custom_fields,
) )
# Mark database as dirty for background sync # Mark database as dirty for background sync
@@ -1429,6 +1442,20 @@ class PasswordManager:
or notes or notes
) )
edit_fields = input("Edit custom fields? (y/N): ").strip().lower()
custom_fields = None
if edit_fields == "y":
custom_fields = []
while True:
label = input(" Field label (leave blank to finish): ").strip()
if not label:
break
value = input(" Field value: ").strip()
hidden = input(" Hidden field? (y/N): ").strip().lower() == "y"
custom_fields.append(
{"label": label, "value": value, "is_hidden": hidden}
)
self.entry_manager.modify_entry( self.entry_manager.modify_entry(
index, index,
blacklisted=new_blacklisted, blacklisted=new_blacklisted,
@@ -1436,6 +1463,7 @@ class PasswordManager:
label=new_label, label=new_label,
period=new_period, period=new_period,
digits=new_digits, digits=new_digits,
custom_fields=custom_fields,
) )
else: else:
website_name = entry.get("website") website_name = entry.get("website")
@@ -1500,12 +1528,27 @@ class PasswordManager:
or notes or notes
) )
edit_fields = input("Edit custom fields? (y/N): ").strip().lower()
custom_fields = None
if edit_fields == "y":
custom_fields = []
while True:
label = input(" Field label (leave blank to finish): ").strip()
if not label:
break
value = input(" Field value: ").strip()
hidden = input(" Hidden field? (y/N): ").strip().lower() == "y"
custom_fields.append(
{"label": label, "value": value, "is_hidden": hidden}
)
self.entry_manager.modify_entry( self.entry_manager.modify_entry(
index, index,
new_username, new_username,
new_url, new_url,
new_blacklisted, new_blacklisted,
new_notes, new_notes,
custom_fields=custom_fields,
) )
# Mark database as dirty for background sync # Mark database as dirty for background sync

View File

@@ -21,7 +21,12 @@ def test_add_and_retrieve_entry():
backup_mgr = BackupManager(Path(tmpdir), cfg_mgr) backup_mgr = BackupManager(Path(tmpdir), cfg_mgr)
entry_mgr = EntryManager(vault, backup_mgr) entry_mgr = EntryManager(vault, backup_mgr)
index = entry_mgr.add_entry("example.com", 12, "user") custom = [
{"label": "api", "value": "123", "is_hidden": True},
{"label": "note", "value": "hello", "is_hidden": False},
]
index = entry_mgr.add_entry("example.com", 12, "user", custom_fields=custom)
entry = entry_mgr.retrieve_entry(index) entry = entry_mgr.retrieve_entry(index)
assert entry == { assert entry == {
@@ -33,6 +38,7 @@ def test_add_and_retrieve_entry():
"type": "password", "type": "password",
"kind": "password", "kind": "password",
"notes": "", "notes": "",
"custom_fields": custom,
} }
data = enc_mgr.load_json_data(entry_mgr.index_file) data = enc_mgr.load_json_data(entry_mgr.index_file)

View File

@@ -52,14 +52,16 @@ def test_manager_workflow(monkeypatch):
"example.com", "example.com",
"", # username "", # username
"", # url "", # url
"", # length (default)
"", # notes "", # notes
"n", # add custom field
"", # length (default)
"0", # retrieve index "0", # retrieve index
"0", # modify index "0", # modify index
"user", # new username "user", # new username
"", # new url "", # new url
"", # blacklist status "", # blacklist status
"", # new notes "", # new notes
"n", # edit custom fields
] ]
) )
monkeypatch.setattr("builtins.input", lambda *args, **kwargs: next(inputs)) monkeypatch.setattr("builtins.input", lambda *args, **kwargs: next(inputs))

View File

@@ -71,6 +71,21 @@ def test_search_by_notes_and_totp():
assert res_totp == [(idx_totp, "GH", None, None, False)] assert res_totp == [(idx_totp, "GH", None, None, False)]
def test_search_by_custom_field():
with TemporaryDirectory() as tmpdir:
tmp_path = Path(tmpdir)
entry_mgr = setup_entry_manager(tmp_path)
custom = [
{"label": "api", "value": "secret123", "is_hidden": True},
{"label": "note", "value": "visible", "is_hidden": False},
]
idx = entry_mgr.add_entry("Example", 8, custom_fields=custom)
result = entry_mgr.search_entries("secret123")
assert result == [(idx, "Example", "", "", False)]
def test_search_no_results(): def test_search_no_results():
with TemporaryDirectory() as tmpdir: with TemporaryDirectory() as tmpdir:
tmp_path = Path(tmpdir) tmp_path = Path(tmpdir)