main
  1#!/usr/bin/env python3
  2"""List Passage entries for Raffi, or copy a selected entry safely."""
  3
  4from __future__ import annotations
  5
  6import base64
  7import json
  8import os
  9import shutil
 10import subprocess
 11import sys
 12from pathlib import Path
 13
 14DATA_HOME = os.environ.get("XDG_DATA_HOME", "~/.local/share")
 15STORE_DIR = Path(os.environ.get("PASSAGE_DIR", f"{DATA_HOME}/passage")).expanduser()
 16
 17
 18def encode_entry(entry: str) -> str:
 19    return base64.urlsafe_b64encode(entry.encode()).decode().rstrip("=")
 20
 21
 22def decode_entry(value: str) -> str:
 23    try:
 24        padded = value + "=" * (-len(value) % 4)
 25        return base64.b64decode(padded, altchars=b"-_", validate=True).decode()
 26    except (UnicodeDecodeError, ValueError) as error:
 27        raise ValueError("invalid Passage entry") from error
 28
 29
 30def entry_path(entry: str) -> Path:
 31    store = STORE_DIR.resolve()
 32    path = (store / f"{entry}.age").resolve()
 33    try:
 34        path.relative_to(store)
 35    except ValueError as error:
 36        raise ValueError("invalid Passage entry") from error
 37    if not path.is_file() or path.suffix != ".age":
 38        raise ValueError("invalid Passage entry")
 39    return path
 40
 41
 42def list_entries(query: str) -> None:
 43    if not STORE_DIR.is_dir():
 44        print(
 45            json.dumps(
 46                {
 47                    "items": [
 48                        {
 49                            "title": "Passage store unavailable",
 50                            "subtitle": f"No store at {STORE_DIR}",
 51                            "valid": False,
 52                        }
 53                    ]
 54                }
 55            )
 56        )
 57        return
 58
 59    entries = []
 60    for path in STORE_DIR.rglob("*.age"):
 61        if path.is_symlink() or ".git" in path.relative_to(STORE_DIR).parts:
 62            continue
 63        entry = str(path.relative_to(STORE_DIR).with_suffix(""))
 64        if query.casefold() not in entry.casefold():
 65            continue
 66        entries.append(
 67            {
 68                "title": entry,
 69                "subtitle": "Copy password from Passage",
 70                "arg": encode_entry(entry),
 71                "valid": True,
 72            }
 73        )
 74    print(json.dumps({"items": sorted(entries, key=lambda item: item["title"])}))
 75
 76
 77def copy_entry(value: str) -> None:
 78    entry = decode_entry(value)
 79    entry_path(entry)
 80    os.environ.setdefault("PASSAGE_DIR", str(STORE_DIR))
 81    os.environ.setdefault("PASSAGE_IDENTITIES_FILE", str(STORE_DIR / "identities"))
 82    subprocess.run(["passage", "show", "--clip", "--", entry], check=True)
 83    if shutil.which("notify-send"):
 84        subprocess.run(
 85            ["notify-send", "Passage", "Password copied to clipboard"],
 86            check=False,
 87            stdout=subprocess.DEVNULL,
 88            stderr=subprocess.DEVNULL,
 89        )
 90
 91
 92def main() -> None:
 93    if len(sys.argv) >= 2 and sys.argv[1] == "--copy":
 94        if len(sys.argv) != 3:
 95            raise ValueError("invalid Passage entry")
 96        copy_entry(sys.argv[2])
 97    else:
 98        list_entries(sys.argv[1] if len(sys.argv) > 1 else "")
 99
100
101if __name__ == "__main__":
102    try:
103        main()
104    except (ValueError, subprocess.CalledProcessError) as error:
105        print(error, file=sys.stderr)
106        raise SystemExit(1) from error