60 lines
1.8 KiB
Python
60 lines
1.8 KiB
Python
import json
|
|
import os
|
|
import struct
|
|
import sys
|
|
|
|
PATH = os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share"), "bugpass", "profiles.json")
|
|
DEFAULTS = {"lowercase": True, "uppercase": True, "digits": True, "symbols": True, "length": 16, "counter": 1}
|
|
|
|
|
|
def load():
|
|
try:
|
|
with open(PATH) as f:
|
|
return json.load(f)
|
|
except FileNotFoundError:
|
|
return []
|
|
|
|
|
|
def store(profiles):
|
|
os.makedirs(os.path.dirname(PATH), exist_ok=True)
|
|
tmp = PATH + ".tmp"
|
|
with open(tmp, "w") as f:
|
|
json.dump(profiles, f, indent=1)
|
|
os.replace(tmp, PATH)
|
|
|
|
|
|
def clean(p):
|
|
# whitelist fields: a master/generated password can never end up on disk
|
|
out = {"site": str(p["site"]), "login": str(p.get("login", ""))}
|
|
for k, d in DEFAULTS.items():
|
|
out[k] = bool(p.get(k, d)) if isinstance(d, bool) else int(p.get(k, d))
|
|
out["length"] = min(35, max(5, out["length"]))
|
|
out["counter"] = max(1, out["counter"])
|
|
return out
|
|
|
|
|
|
def handle(m):
|
|
profiles = load()
|
|
if m.get("cmd") == "list":
|
|
return {"profiles": profiles}
|
|
if m.get("cmd") == "save":
|
|
p = clean(m["profile"])
|
|
key = (p["site"], p["login"])
|
|
elif m.get("cmd") == "delete":
|
|
p, key = None, (m["site"], m["login"])
|
|
else:
|
|
return {"error": "unknown cmd"}
|
|
profiles = [q for q in profiles if (q["site"], q["login"]) != key] + ([p] if p else [])
|
|
store(profiles)
|
|
return {"ok": True}
|
|
|
|
|
|
while (head := sys.stdin.buffer.read(4)) and len(head) == 4:
|
|
try:
|
|
reply = handle(json.loads(sys.stdin.buffer.read(struct.unpack("=I", head)[0])))
|
|
except Exception as e:
|
|
reply = {"error": str(e)}
|
|
data = json.dumps(reply).encode()
|
|
sys.stdout.buffer.write(struct.pack("=I", len(data)) + data)
|
|
sys.stdout.buffer.flush()
|