Commit 2eb48c1052ae
Changed files (4)
dots
config
raffi
dots/config/raffi/scripts/passage-raffi
@@ -0,0 +1,106 @@
+#!/usr/bin/env python3
+"""List Passage entries for Raffi, or copy a selected entry safely."""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+DATA_HOME = os.environ.get("XDG_DATA_HOME", "~/.local/share")
+STORE_DIR = Path(os.environ.get("PASSAGE_DIR", f"{DATA_HOME}/passage")).expanduser()
+
+
+def encode_entry(entry: str) -> str:
+ return base64.urlsafe_b64encode(entry.encode()).decode().rstrip("=")
+
+
+def decode_entry(value: str) -> str:
+ try:
+ padded = value + "=" * (-len(value) % 4)
+ return base64.b64decode(padded, altchars=b"-_", validate=True).decode()
+ except (UnicodeDecodeError, ValueError) as error:
+ raise ValueError("invalid Passage entry") from error
+
+
+def entry_path(entry: str) -> Path:
+ store = STORE_DIR.resolve()
+ path = (store / f"{entry}.age").resolve()
+ try:
+ path.relative_to(store)
+ except ValueError as error:
+ raise ValueError("invalid Passage entry") from error
+ if not path.is_file() or path.suffix != ".age":
+ raise ValueError("invalid Passage entry")
+ return path
+
+
+def list_entries(query: str) -> None:
+ if not STORE_DIR.is_dir():
+ print(
+ json.dumps(
+ {
+ "items": [
+ {
+ "title": "Passage store unavailable",
+ "subtitle": f"No store at {STORE_DIR}",
+ "valid": False,
+ }
+ ]
+ }
+ )
+ )
+ return
+
+ entries = []
+ for path in STORE_DIR.rglob("*.age"):
+ if path.is_symlink() or ".git" in path.relative_to(STORE_DIR).parts:
+ continue
+ entry = str(path.relative_to(STORE_DIR).with_suffix(""))
+ if query.casefold() not in entry.casefold():
+ continue
+ entries.append(
+ {
+ "title": entry,
+ "subtitle": "Copy password from Passage",
+ "arg": encode_entry(entry),
+ "valid": True,
+ }
+ )
+ print(json.dumps({"items": sorted(entries, key=lambda item: item["title"])}))
+
+
+def copy_entry(value: str) -> None:
+ entry = decode_entry(value)
+ entry_path(entry)
+ os.environ.setdefault("PASSAGE_DIR", str(STORE_DIR))
+ os.environ.setdefault("PASSAGE_IDENTITIES_FILE", str(STORE_DIR / "identities"))
+ subprocess.run(["passage", "show", "--clip", "--", entry], check=True)
+ if shutil.which("notify-send"):
+ subprocess.run(
+ ["notify-send", "Passage", "Password copied to clipboard"],
+ check=False,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+
+
+def main() -> None:
+ if len(sys.argv) >= 2 and sys.argv[1] == "--copy":
+ if len(sys.argv) != 3:
+ raise ValueError("invalid Passage entry")
+ copy_entry(sys.argv[2])
+ else:
+ list_entries(sys.argv[1] if len(sys.argv) > 1 else "")
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except (ValueError, subprocess.CalledProcessError) as error:
+ print(error, file=sys.stderr)
+ raise SystemExit(1) from error
dots/config/raffi/scripts/passage-raffi-copy
@@ -0,0 +1,3 @@
+#!/usr/bin/env sh
+# Copy the selected opaque Passage entry through Passage's managed clipboard.
+exec "$(dirname "$0")/passage-raffi" --copy "$@"
dots/config/raffi/tests/test_passage_raffi.py
@@ -0,0 +1,135 @@
+"""Tests for the Passage Raffi script filter and copy action."""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import subprocess
+import tempfile
+import unittest
+from pathlib import Path
+
+SCRIPTS = Path(__file__).parents[1] / "scripts"
+FILTER = SCRIPTS / "passage-raffi"
+COPY = SCRIPTS / "passage-raffi-copy"
+
+
+class PassageRaffiTests(unittest.TestCase):
+ def make_store(self, directory: Path) -> Path:
+ store = directory / "passage"
+ (store / "web").mkdir(parents=True)
+ (store / "web" / "github.age").touch()
+ (store / "mail.age").touch()
+ (store / ".git").mkdir()
+ (store / ".git" / "ignored.age").touch()
+ return store
+
+ def run_filter(self, store: Path, query: str = "") -> dict[str, object]:
+ completed = subprocess.run(
+ [str(FILTER), query],
+ check=True,
+ capture_output=True,
+ text=True,
+ env={**os.environ, "PASSAGE_DIR": str(store)},
+ )
+ return json.loads(completed.stdout)
+
+ def test_lists_age_entries_without_exposing_paths_in_action_values(self) -> None:
+ with tempfile.TemporaryDirectory() as temporary_directory:
+ result = self.run_filter(self.make_store(Path(temporary_directory)))
+
+ self.assertEqual(
+ [item["title"] for item in result["items"]], ["mail", "web/github"]
+ )
+ self.assertEqual(
+ [item["subtitle"] for item in result["items"]],
+ ["Copy password from Passage", "Copy password from Passage"],
+ )
+ self.assertTrue(all(item["valid"] for item in result["items"]))
+ self.assertTrue(all("/" not in item["arg"] for item in result["items"]))
+
+ def test_filters_entry_names(self) -> None:
+ with tempfile.TemporaryDirectory() as temporary_directory:
+ result = self.run_filter(self.make_store(Path(temporary_directory)), "git")
+
+ self.assertEqual([item["title"] for item in result["items"]], ["web/github"])
+
+ def test_defaults_to_the_xdg_data_passage_store(self) -> None:
+ with tempfile.TemporaryDirectory() as temporary_directory:
+ home = Path(temporary_directory)
+ self.make_store(home / ".local" / "share")
+ environment = {**os.environ, "HOME": str(home)}
+ environment.pop("PASSAGE_DIR", None)
+ environment.pop("XDG_DATA_HOME", None)
+ completed = subprocess.run(
+ [str(FILTER)],
+ check=True,
+ capture_output=True,
+ text=True,
+ env=environment,
+ )
+
+ result = json.loads(completed.stdout)
+ self.assertEqual(
+ [item["title"] for item in result["items"]], ["mail", "web/github"]
+ )
+
+ def test_copy_decodes_the_selected_entry_and_uses_passage_clipboard(self) -> None:
+ with tempfile.TemporaryDirectory() as temporary_directory:
+ temporary_path = Path(temporary_directory)
+ store = self.make_store(temporary_path)
+ bin_directory = temporary_path / "bin"
+ bin_directory.mkdir()
+ arguments = temporary_path / "passage-arguments"
+ notification = temporary_path / "notification-arguments"
+ passage = bin_directory / "passage"
+ passage.write_text(
+ f'#!/bin/sh\nprintf "%s\\n" "$@" > "{arguments}"\n', encoding="utf-8"
+ )
+ passage.chmod(0o755)
+ notify_send = bin_directory / "notify-send"
+ notify_send.write_text(
+ f'#!/bin/sh\nprintf "%s\\n" "$@" > "{notification}"\n', encoding="utf-8"
+ )
+ notify_send.chmod(0o755)
+ encoded = base64.urlsafe_b64encode(b"web/github").decode().rstrip("=")
+
+ subprocess.run(
+ [str(COPY), encoded],
+ check=True,
+ env={
+ **os.environ,
+ "PASSAGE_DIR": str(store),
+ "PATH": f"{bin_directory}:{os.environ['PATH']}",
+ },
+ )
+
+ self.assertEqual(
+ arguments.read_text(encoding="utf-8").splitlines(),
+ ["show", "--clip", "--", "web/github"],
+ )
+ self.assertEqual(
+ notification.read_text(encoding="utf-8").splitlines(),
+ ["Passage", "Password copied to clipboard"],
+ )
+
+ def test_copy_rejects_an_entry_outside_the_store(self) -> None:
+ with tempfile.TemporaryDirectory() as temporary_directory:
+ temporary_path = Path(temporary_directory)
+ store = self.make_store(temporary_path)
+ encoded = base64.urlsafe_b64encode(b"../outside").decode().rstrip("=")
+ completed = subprocess.run(
+ [str(COPY), encoded],
+ check=False,
+ capture_output=True,
+ text=True,
+ env={**os.environ, "PASSAGE_DIR": str(store)},
+ )
+
+ self.assertNotEqual(completed.returncode, 0)
+ self.assertIn("invalid Passage entry", completed.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()
dots/config/raffi/raffi.yaml
@@ -140,6 +140,11 @@ addons:
command: ~/.config/raffi/scripts/yubikey-oath-raffi
icon: security-high
action: ~/.config/raffi/scripts/yubikey-oath-copy {value}
+ - name: Passage Passwords
+ keyword: passage
+ command: ~/.config/raffi/scripts/passage-raffi
+ icon: dialog-password
+ action: ~/.config/raffi/scripts/passage-raffi-copy {value}
- name: GitHub Pull Requests
keyword: pr
command: ~/.config/raffi/scripts/github/pr.py