repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
vault-pdf.pyPython186 lines7.4 KiBraw download
#!/usr/bin/env python3
"""Browse DAEMONSEC-VAULT PDF cheat sheets; filenames are data, never shell code."""

import argparse
from collections import Counter
import hashlib
import os
from pathlib import Path
import re
import shlex
import shutil
import subprocess
import sys
import unicodedata


def clean(text):
    return "".join(c if c.isprintable() else " " for c in str(text))


def slug(text):
    text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode()
    return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")[:70] or "document"


def vault_root():
    override = os.environ.get("DAEMONSEC_VAULT") or os.environ.get("NETRUNNER_VAULT")
    if override:
        root = Path(override).expanduser().resolve()
        renamed = Path.home() / "git" / "DAEMONSEC-VAULT"
        # Older shells may still export the former default after the rename.
        if root == Path.home() / "git" / "NetrunnerVault" and not root.is_dir() and renamed.is_dir():
            return renamed.resolve()
        return root
    candidates = [Path.home() / "git" / name for name in ("DAEMONSEC-VAULT", "NetrunnerVault")]
    return next((root for root in candidates if root.is_dir()), candidates[0]).resolve()


def catalog(root):
    if not root.is_dir():
        raise ValueError(f"Vault not found: {root}. Set DAEMONSEC_VAULT or NETRUNNER_VAULT to its location.")
    library = root / "06PdfCheatSheets"
    if not library.is_dir():
        raise ValueError(f"PDF cheat-sheet folder not found: {library}")
    paths = []
    for directory, dirs, files in os.walk(library):
        dirs[:] = sorted(d for d in dirs if not d.startswith("."))
        for name in files:
            # Keep university CMP documents out of the launcher and aliases.
            if name.casefold().startswith("cmp"):
                continue
            path = Path(directory) / name
            if path.suffix.lower() == ".pdf" and path.is_file():
                paths.append(path)
    paths.sort(key=lambda p: str(p.relative_to(root)).casefold())
    counts = Counter(slug(p.stem) for p in paths)
    result = {}
    reserved = {"pdf-list", "pdf-refresh", "pdf-fzf"}
    for path in paths:
        name = "pdf-" + slug(path.stem)
        relative = str(path.relative_to(root))
        if counts[slug(path.stem)] > 1 or name in reserved:
            name += "-" + hashlib.sha256(relative.encode()).hexdigest()[:8]
        # Also handle a literal filename matching another document's suffix.
        while name in result or name in reserved:
            name += "-" + hashlib.sha256(relative.encode()).hexdigest()[:8]
        result[name] = path
    return result


def find_document(documents, name):
    try:
        return documents[name]
    except KeyError:
        raise ValueError(f"Unknown PDF shortcut: {name}. Run pdf-refresh, then pdf-list.") from None


def open_document(path):
    opener = shutil.which("open" if sys.platform == "darwin" else "xdg-open")
    if not opener:
        raise ValueError("No desktop opener found (xdg-open on Linux, open on macOS).")
    # Absolute paths cannot be mistaken for command options. No shell involved.
    process = subprocess.Popen(
        [opener, str(path)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
        start_new_session=True,
    )
    try:
        status = process.wait(timeout=0.3)
        if status:
            raise ValueError(f"PDF viewer failed to open {clean(path.name)} (exit {status}).")
    except subprocess.TimeoutExpired:
        # Some desktop openers remain attached to the viewer until it closes.
        pass


def preview(name, path, root):
    print(f"{clean(path.stem)}\n{'─' * 48}\nShortcut: {name}")
    print(f"Folder:   {clean(path.parent.relative_to(root))}")
    print(f"File:     {clean(path.name)}\nSize:     {path.stat().st_size / 1024:,.0f} KiB\n", flush=True)
    extractor = shutil.which("pdftotext")
    if not extractor:
        print("Install poppler-utils for a text preview. Enter still opens the PDF.")
        return
    try:
        output = subprocess.run(
            [extractor, "-f", "1", "-l", "2", "-layout", str(path), "-"],
            capture_output=True, text=True, errors="replace", timeout=4, check=True,
        ).stdout
        if output.strip():
            print("\n".join(clean(line) for line in output.splitlines()[:180]))
        else:
            print("No extractable text (possibly a scanned PDF). Enter opens the document.")
    except (subprocess.SubprocessError, OSError):
        print("Text preview unavailable. Enter opens the original PDF.")


def menu(documents, root, query):
    if not documents:
        print(f"No PDFs found in {root}.")
        return
    finder = shutil.which("fzf")
    if not finder:
        raise ValueError("fzf is not installed. Use pdf-list and an individual shortcut instead.")
    rows = [
        f"{name}\t{clean(re.sub(r'[_-]+', ' ', path.stem))}\t{clean(path.parent.relative_to(root))}"
        for name, path in documents.items()
    ]
    preview_cmd = shlex.join([sys.executable, str(Path(__file__).resolve()), "preview"])
    result = subprocess.run(
        [finder, "--read0", "--print0", "--multi", "--delimiter=\t", "--with-nth=2,3,1",
         "--layout=reverse", "--height=90%", "--border=rounded",
         f"--border-label= DAEMONSEC / PDF CHEAT SHEETS · {len(documents)} documents ",
         "--prompt=pdf> ", "--pointer=▶", "--cycle",
         "--header=Enter: open · Tab: select several · Shift-↑↓: scroll preview · Esc: cancel\nSearch title / folder / alias · Ctrl-/: toggle preview",
         "--bind=ctrl-/:toggle-preview", "--preview=" + preview_cmd + " {1}",
         "--preview-window=up,60%,border-bottom,wrap", "--query=" + query],
        input="\0".join(rows) + "\0", text=True, stdout=subprocess.PIPE,
    )
    if result.returncode in (1, 130):
        return
    if result.returncode:
        raise ValueError(f"fzf exited with status {result.returncode}.")
    for row in result.stdout.split("\0"):
        if row:
            name = row.split("\t", 1)[0]
            open_document(find_document(documents, name))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("action", nargs="?", default="menu", choices=["menu", "list", "aliases", "open", "preview"])
    parser.add_argument("words", nargs="*")
    args = parser.parse_args()
    root = vault_root()
    try:
        documents = catalog(root)
        if args.action == "aliases":
            print("\n".join(documents))
        elif args.action == "list":
            query = " ".join(args.words).casefold()
            for name, path in documents.items():
                line = f"{name:80}  {clean(path.relative_to(root))}"
                if query in line.casefold():
                    print(line)
        elif args.action in ("open", "preview"):
            if len(args.words) != 1:
                parser.error(f"{args.action} requires one pdf- shortcut")
            name = args.words[0]
            path = find_document(documents, name)
            if args.action == "open":
                open_document(path)
            else:
                preview(name, path, root)
        else:
            menu(documents, root, " ".join(args.words))
    except (ValueError, OSError, subprocess.SubprocessError) as error:
        print(f"vault-pdf: {error}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        sys.exit(130)