OTPRunner 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
otprunner/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """OTPRunner: códigos TOTP en KRunner con secretos en el keystore del sistema."""
2
+
3
+ __version__ = "0.2.0"
4
+
5
+ # Nombre de producto para todo lo visible (notificaciones, diálogos, KRunner).
6
+ # Los identificadores técnicos (comando, paquete, DBus, ficheros) van en minúsculas.
7
+ APP_NAME = "OTPRunner"
otprunner/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
otprunner/adding.py ADDED
@@ -0,0 +1,96 @@
1
+ """Flujo de alta compartido por el runner y la CLI: obtener URIs → importar → resumir."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from collections.abc import Callable
8
+
9
+ from . import camera, capture, importer
10
+ from .dbusutil import name_available
11
+ from .i18n import _, ngettext
12
+ from .store import Store
13
+
14
+ SOURCES = ("screen", "clipboard", "camera")
15
+
16
+
17
+ @dataclass
18
+ class Outcome:
19
+ parsed: importer.Parsed
20
+ result: importer.ImportResult = field(default_factory=importer.ImportResult)
21
+ notes: list[str] = field(default_factory=list)
22
+
23
+ @property
24
+ def ok(self) -> bool:
25
+ return bool(self.result.added or self.result.updated or self.result.skipped)
26
+
27
+ def summary(self) -> tuple[str, str]:
28
+ """(título, cuerpo) para notificación o consola."""
29
+ r, p = self.result, self.parsed
30
+ lines = []
31
+ if r.added:
32
+ if len(r.added) == 1:
33
+ title = _("Added: {name}").format(name=r.added[0])
34
+ else:
35
+ title = ngettext("Added {n} account", "Added {n} accounts", len(r.added)).format(n=len(r.added))
36
+ if len(r.added) > 1:
37
+ lines.append(", ".join(r.added))
38
+ elif r.updated:
39
+ title = ngettext("Updated {n} account", "Updated {n} accounts", len(r.updated)).format(n=len(r.updated))
40
+ elif r.skipped:
41
+ title = _("Nothing new to add")
42
+ elif p.errors:
43
+ title = _("Could not add the account")
44
+ else:
45
+ title = _("No otpauth code found")
46
+ for wanted, final in r.renamed:
47
+ lines.append(_("“{wanted}” already existed: saved as “{final}”").format(wanted=wanted, final=final))
48
+ if r.updated:
49
+ lines.append(_("Same secret, code updated: {names}").format(names=", ".join(r.updated)))
50
+ if r.skipped:
51
+ lines.append(_("Already present: {names}").format(names=", ".join(r.skipped)))
52
+ for b in p.batches:
53
+ if b.batch_size > 1:
54
+ if b.batch_index + 1 < b.batch_size:
55
+ msg = _("Google export: batch {i} of {n} — capture the next QR code")
56
+ else:
57
+ msg = _("Google export: batch {i} of {n}")
58
+ lines.append(msg.format(i=b.batch_index + 1, n=b.batch_size))
59
+ lines.extend(p.errors)
60
+ if self.ok:
61
+ lines.extend(self.notes)
62
+ return title, "\n".join(lines)
63
+
64
+
65
+ async def acquire(source: str, bus, *, uri: str | None = None, device: str | None = None,
66
+ progress: Callable[[str], None] | None = None) -> tuple[importer.Parsed, list[str]]:
67
+ """Devuelve las cuentas encontradas y avisos para el usuario."""
68
+ if source == "uri":
69
+ return importer.parse_text(uri or ""), []
70
+ if source == "camera":
71
+ texts = await camera.scan(device, progress)
72
+ if not texts:
73
+ raise capture.CaptureCancelled("cancelled")
74
+ return importer.parse_text("\n".join(texts)), []
75
+ if source == "screen":
76
+ return importer.parse_text("\n".join(await capture.from_screen(bus))), []
77
+ if source == "clipboard":
78
+ parsed = importer.parse_text(await capture.clipboard_text(bus))
79
+ if not parsed.accounts and not parsed.errors:
80
+ return importer.parse_text("\n".join(await capture.clipboard_image_qr())), []
81
+ notes = []
82
+ # Klipper no permite borrar una entrada concreta del historial (ni vaciar el
83
+ # portapapeles si «evitar portapapeles vacío» está activo): solo podemos avisar.
84
+ if parsed.accounts and bus is not None and await name_available(bus, "org.kde.klipper"):
85
+ notes.append(_("The URI with the secret is still in the Klipper history: delete it from its menu."))
86
+ return parsed, notes
87
+ raise ValueError(f"unknown source: {source}")
88
+
89
+
90
+ async def add(store: Store, source: str, bus, *, name: str | None = None, uri: str | None = None,
91
+ device: str | None = None, progress: Callable[[str], None] | None = None) -> Outcome:
92
+ parsed, notes = await acquire(source, bus, uri=uri, device=device, progress=progress)
93
+ out = Outcome(parsed, notes=notes)
94
+ if parsed.accounts:
95
+ out.result = await importer.import_accounts(store, parsed.accounts, name=name or None)
96
+ return out
otprunner/camera.py ADDED
@@ -0,0 +1,185 @@
1
+ """Lectura de QR con la cámara: zbarcam → OpenCV (opcional: ``pipx inject otprunner opencv-python``).
2
+
3
+ La cámara sigue abierta hasta leer un QR otpauth://, o todos los lotes de una
4
+ exportación de Google (avisando del progreso), o hasta que el usuario cierra la ventana.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import glob
11
+ import importlib.util
12
+ import logging
13
+ import shutil
14
+ from collections.abc import Callable
15
+
16
+ from . import APP_NAME, migration
17
+ from .i18n import _
18
+ from .otpauth import OtpError
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+ SCAN_TIMEOUT = 180
23
+ def window_title() -> str:
24
+ return _("{app}: show the QR code to the camera (Esc or close to cancel)").format(app=APP_NAME)
25
+
26
+
27
+ class CameraError(RuntimeError):
28
+ pass
29
+
30
+
31
+ def devices() -> list[str]:
32
+ return sorted(glob.glob("/dev/video*"), key=lambda d: int(d.removeprefix("/dev/video") or 0))
33
+
34
+
35
+ def providers() -> list[str]:
36
+ out = []
37
+ if shutil.which("zbarcam"):
38
+ out.append("zbarcam")
39
+ if importlib.util.find_spec("cv2") is not None:
40
+ out.append("opencv")
41
+ return out
42
+
43
+
44
+ def install_hint() -> str:
45
+ if shutil.which("apt"):
46
+ pkg = "sudo apt install zbar-tools"
47
+ elif shutil.which("dnf"):
48
+ pkg = "sudo dnf install zbar"
49
+ elif shutil.which("pacman"):
50
+ pkg = "sudo pacman -S zbar"
51
+ else:
52
+ pkg = _("install zbar (zbarcam)")
53
+ return pkg + " — " + _("or: {command}").format(command="pipx inject otprunner opencv-python")
54
+
55
+
56
+ class Collector:
57
+ """Acumula lecturas hasta tener algo completo que importar."""
58
+
59
+ def __init__(self, progress: Callable[[str], None] | None = None) -> None:
60
+ self.texts: list[str] = []
61
+ self._seen: set[str] = set()
62
+ self._batches: dict[int, set[int]] = {}
63
+ self._sizes: dict[int, int] = {}
64
+ self.progress = progress or (lambda msg: None)
65
+ self.done = False
66
+
67
+ def feed(self, text: str) -> bool:
68
+ text = text.strip()
69
+ if not text or text in self._seen:
70
+ return self.done
71
+ self._seen.add(text)
72
+ low = text.lower()
73
+ if low.startswith("otpauth://"):
74
+ self.texts.append(text)
75
+ self.done = True
76
+ elif low.startswith("otpauth-migration://"):
77
+ try:
78
+ b = migration.decode(text)
79
+ except OtpError as e:
80
+ log.info("invalid migration QR code: %s", e)
81
+ return self.done
82
+ self.texts.append(text)
83
+ got = self._batches.setdefault(b.batch_id, set())
84
+ got.add(b.batch_index)
85
+ self._sizes[b.batch_id] = b.batch_size
86
+ if len(got) >= b.batch_size:
87
+ self.done = True
88
+ else:
89
+ self.progress(_("Batch {i} of {n} read ({got}/{n}): show the next QR code").format(
90
+ i=b.batch_index + 1, n=b.batch_size, got=len(got)))
91
+ else:
92
+ log.info("QR code ignored: not otpauth")
93
+ return self.done
94
+
95
+
96
+ async def _zbarcam(device: str | None, col: Collector) -> None:
97
+ # Salida normal («QR-Code:<datos>\n»): --raw no garantiza un salto de línea por lectura.
98
+ cmd = ["zbarcam", "-q", "--nodbus", "-Sdisable", "-Sqrcode.enable"]
99
+ if device:
100
+ cmd.append(device)
101
+ proc = await asyncio.create_subprocess_exec(
102
+ *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
103
+ try:
104
+ while True:
105
+ line = await proc.stdout.readline()
106
+ if not line:
107
+ break
108
+ text = line.decode(errors="replace").strip()
109
+ prefix, sep, data = text.partition(":")
110
+ if sep and prefix.replace("-", "").isalnum() and not prefix.lower().startswith("otpauth"):
111
+ text = data # quitar el prefijo de simbología («QR-Code:»)
112
+ if col.feed(text):
113
+ break
114
+ finally:
115
+ if proc.returncode is None:
116
+ proc.terminate()
117
+ try:
118
+ await asyncio.wait_for(proc.wait(), 5)
119
+ except asyncio.TimeoutError:
120
+ proc.kill()
121
+ try:
122
+ err = (await asyncio.wait_for(proc.stderr.read(), 2)).decode(errors="replace").strip()
123
+ except asyncio.TimeoutError: # algún hijo mantiene stderr abierto
124
+ err = ""
125
+ if proc.returncode not in (0, None, -15) and not col.texts:
126
+ raise CameraError(_("zbarcam failed ({rc}): {detail}").format(
127
+ rc=proc.returncode, detail=err.splitlines()[-1] if err else _("no details")))
128
+
129
+
130
+ def _opencv_blocking(device: str | None, col: Collector, deadline: float) -> None:
131
+ import time
132
+
133
+ import cv2
134
+ import zxingcpp
135
+
136
+ idx = int(device.removeprefix("/dev/video")) if device else 0
137
+ cap = cv2.VideoCapture(idx)
138
+ if not cap.isOpened():
139
+ raise CameraError(_("could not open the camera {device}").format(device=device or idx))
140
+ try:
141
+ title = window_title()
142
+ cv2.namedWindow(title, cv2.WINDOW_AUTOSIZE)
143
+ while time.monotonic() < deadline:
144
+ ok, frame = cap.read()
145
+ if not ok:
146
+ raise CameraError(_("the camera returns no images"))
147
+ cv2.imshow(title, frame)
148
+ for r in zxingcpp.read_barcodes(frame, formats=zxingcpp.BarcodeFormat.QRCode):
149
+ if r.text and col.feed(r.text):
150
+ return
151
+ key = cv2.waitKey(30) & 0xFF
152
+ if key == 27 or cv2.getWindowProperty(title, cv2.WND_PROP_VISIBLE) < 1:
153
+ return
154
+ finally:
155
+ cap.release()
156
+ cv2.destroyAllWindows()
157
+
158
+
159
+ async def scan(device: str | None = None, progress: Callable[[str], None] | None = None,
160
+ timeout: float = SCAN_TIMEOUT) -> list[str]:
161
+ """Devuelve los textos otpauth leídos (vacío si el usuario cerró sin leer nada)."""
162
+ provs = providers()
163
+ if not provs:
164
+ raise CameraError(_("no QR reader for the camera: {hint}").format(hint=install_hint()))
165
+ if not devices():
166
+ raise CameraError(_("no camera found (/dev/video*)"))
167
+ col = Collector(progress)
168
+ prov = provs[0]
169
+ log.info("reading QR code with %s (%s)", prov, device or "default camera")
170
+ try:
171
+ if prov == "zbarcam":
172
+ await asyncio.wait_for(_zbarcam(device, col), timeout)
173
+ else:
174
+ import time
175
+
176
+ loop = asyncio.get_running_loop()
177
+ # El progreso llega desde el hilo de OpenCV: reencaminarlo al bucle.
178
+ if progress:
179
+ col.progress = lambda msg: loop.call_soon_threadsafe(progress, msg)
180
+ # El plazo se comprueba dentro del hilo: cancelar el future no liberaría la cámara.
181
+ await loop.run_in_executor(None, _opencv_blocking, device, col, time.monotonic() + timeout)
182
+ except asyncio.TimeoutError:
183
+ if not col.texts:
184
+ raise CameraError(_("timed out without reading any QR code")) from None
185
+ return col.texts
otprunner/capture.py ADDED
@@ -0,0 +1,230 @@
1
+ """Obtención de URIs OTP desde una captura de pantalla o el portapapeles.
2
+
3
+ Captura: spectacle (región) → portal XDG Screenshot (interactivo; vale en Wayland) →
4
+ gnome-screenshot → maim. Las imágenes contienen secretos: se escriben en
5
+ ``$XDG_RUNTIME_DIR/otprunner`` (tmpfs, 0700) y se borran siempre, incluida la que
6
+ haya guardado el portal donde sea.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import logging
13
+ import os
14
+ import secrets
15
+ import shutil
16
+ import tempfile
17
+ from pathlib import Path
18
+ from urllib.parse import unquote, urlsplit
19
+
20
+ from dbus_fast import Message, MessageType, Variant
21
+
22
+ from .dbusutil import DBusCallError, call, name_available
23
+ from .i18n import _
24
+
25
+ log = logging.getLogger(__name__)
26
+
27
+ CAPTURE_TIMEOUT = 180 # el usuario tiene que seleccionar la zona
28
+
29
+
30
+ class CaptureError(RuntimeError):
31
+ pass
32
+
33
+
34
+ class CaptureCancelled(CaptureError):
35
+ pass
36
+
37
+
38
+ class NoQRFound(CaptureError):
39
+ pass
40
+
41
+
42
+ def private_dir() -> Path:
43
+ base = os.environ.get("XDG_RUNTIME_DIR") or tempfile.gettempdir()
44
+ d = Path(base) / "otprunner"
45
+ d.mkdir(mode=0o700, exist_ok=True)
46
+ os.chmod(d, 0o700)
47
+ return d
48
+
49
+
50
+ # --- decodificación -------------------------------------------------------------
51
+ def decode_qr(path: Path) -> list[str]:
52
+ """Textos de todos los QR de la imagen."""
53
+ import zxingcpp
54
+ from PIL import Image
55
+
56
+ with Image.open(path) as img:
57
+ img.load()
58
+ results = zxingcpp.read_barcodes(img)
59
+ if not results: # QR pequeños o con poco contraste: probar ampliado y en grises
60
+ big = img.convert("L").resize((img.width * 2, img.height * 2))
61
+ results = zxingcpp.read_barcodes(big)
62
+ return [r.text for r in results if r.text]
63
+
64
+
65
+ # --- captura ------------------------------------------------------------------
66
+ async def _run(cmd: list[str], timeout: float = CAPTURE_TIMEOUT) -> int:
67
+ proc = await asyncio.create_subprocess_exec(
68
+ *cmd, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE
69
+ )
70
+ try:
71
+ _out, err = await asyncio.wait_for(proc.communicate(), timeout)
72
+ except asyncio.TimeoutError:
73
+ proc.kill()
74
+ raise CaptureError(_("{tool}: timed out").format(tool=cmd[0])) from None
75
+ if proc.returncode:
76
+ log.debug("%s rc=%s: %s", cmd[0], proc.returncode, err.decode(errors="replace").strip())
77
+ return proc.returncode
78
+
79
+
80
+ def _x11() -> bool:
81
+ return bool(os.environ.get("DISPLAY")) and not os.environ.get("WAYLAND_DISPLAY")
82
+
83
+
84
+ async def _portal(bus, out: Path) -> Path:
85
+ """org.freedesktop.portal.Screenshot interactivo. Devuelve la ruta que haya elegido el portal."""
86
+ token = "otprunner" + secrets.token_hex(4)
87
+ sender = bus.unique_name.lstrip(":").replace(".", "_")
88
+ req_path = f"/org/freedesktop/portal/desktop/request/{sender}/{token}"
89
+ loop = asyncio.get_running_loop()
90
+ fut: asyncio.Future = loop.create_future()
91
+
92
+ def handler(msg: Message):
93
+ if (msg.message_type == MessageType.SIGNAL and msg.path == req_path
94
+ and msg.member == "Response" and not fut.done()):
95
+ fut.set_result(msg.body)
96
+
97
+ rule = f"type='signal',interface='org.freedesktop.portal.Request',member='Response',path='{req_path}'"
98
+ await call(bus, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "AddMatch", "s", [rule])
99
+ bus.add_message_handler(handler)
100
+ try:
101
+ await call(bus, "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop",
102
+ "org.freedesktop.portal.Screenshot", "Screenshot", "sa{sv}",
103
+ ["", {"handle_token": Variant("s", token), "interactive": Variant("b", True)}])
104
+ code, results = await asyncio.wait_for(fut, CAPTURE_TIMEOUT)
105
+ except asyncio.TimeoutError:
106
+ raise CaptureError(_("{tool}: timed out").format(tool="portal")) from None
107
+ finally:
108
+ bus.remove_message_handler(handler)
109
+ if code == 1:
110
+ raise CaptureCancelled("cancelled")
111
+ if code != 0 or "uri" not in results:
112
+ raise CaptureError(_("the portal returned no screenshot (code {code})").format(code=code))
113
+ parts = urlsplit(results["uri"].value)
114
+ return Path(unquote(parts.path))
115
+
116
+
117
+ async def providers(bus) -> list[str]:
118
+ out = []
119
+ if shutil.which("spectacle"):
120
+ out.append("spectacle")
121
+ if bus is not None and await name_available(bus, "org.freedesktop.portal.Desktop"):
122
+ out.append("portal")
123
+ if _x11() and shutil.which("gnome-screenshot"):
124
+ out.append("gnome-screenshot")
125
+ if _x11() and shutil.which("maim"):
126
+ out.append("maim")
127
+ return out
128
+
129
+
130
+ async def screenshot(bus, provider: str, out: Path) -> Path:
131
+ """Captura una zona elegida por el usuario. Devuelve la ruta de la imagen."""
132
+ if provider == "portal":
133
+ return await _portal(bus, out)
134
+ cmd = {
135
+ "spectacle": ["spectacle", "-b", "-n", "-r", "-o", str(out)],
136
+ "gnome-screenshot": ["gnome-screenshot", "-a", "-f", str(out)],
137
+ "maim": ["maim", "-s", str(out)],
138
+ }[provider]
139
+ rc = await _run(cmd)
140
+ if not out.exists() or out.stat().st_size == 0:
141
+ raise CaptureCancelled("cancelled") if rc in (0, 1) else CaptureError(
142
+ _("{tool}: exit code {rc}").format(tool=provider, rc=rc))
143
+ return out
144
+
145
+
146
+ async def from_screen(bus, delay: float = 0.4) -> list[str]:
147
+ """Pide al usuario una zona de pantalla y devuelve los textos de los QR que haya."""
148
+ provs = await providers(bus)
149
+ if not provs:
150
+ raise CaptureError(_("no screen capture tool: install spectacle or xdg-desktop-portal"))
151
+ await asyncio.sleep(delay) # que KRunner termine de cerrarse
152
+ out = private_dir() / f"capture-{secrets.token_hex(6)}.png"
153
+ errors = []
154
+ for prov in provs:
155
+ img = None
156
+ try:
157
+ img = await screenshot(bus, prov, out)
158
+ texts = await asyncio.get_running_loop().run_in_executor(None, decode_qr, img)
159
+ if not texts:
160
+ raise NoQRFound(_("no QR code detected in the captured area"))
161
+ return texts
162
+ except (CaptureCancelled, NoQRFound):
163
+ raise
164
+ except CaptureError as e:
165
+ errors.append(f"{prov}: {e}")
166
+ except (OSError, DBusCallError) as e:
167
+ errors.append(f"{prov}: {e}")
168
+ finally:
169
+ for p in {out, img} - {None}:
170
+ try:
171
+ p.unlink(missing_ok=True)
172
+ except OSError as e:
173
+ log.warning("could not delete %s: %s", p, e)
174
+ raise CaptureError("; ".join(errors))
175
+
176
+
177
+ # --- portapapeles ---------------------------------------------------------------
178
+ async def _read_cmd(cmd: list[str]) -> bytes | None:
179
+ if not shutil.which(cmd[0]):
180
+ return None
181
+ try:
182
+ proc = await asyncio.create_subprocess_exec(
183
+ *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL)
184
+ data, _err = await asyncio.wait_for(proc.communicate(), 5)
185
+ return data if proc.returncode == 0 and data else None
186
+ except (OSError, asyncio.TimeoutError):
187
+ return None
188
+
189
+
190
+ async def clipboard_text(bus) -> str:
191
+ if bus is not None:
192
+ try:
193
+ if await name_available(bus, "org.kde.klipper"):
194
+ (txt,) = await call(bus, "org.kde.klipper", "/klipper", "org.kde.klipper.klipper",
195
+ "getClipboardContents")
196
+ if txt:
197
+ return txt
198
+ except DBusCallError:
199
+ pass
200
+ for cmd in (["wl-paste", "-n"], ["xclip", "-selection", "clipboard", "-o"], ["xsel", "-bo"]):
201
+ if cmd[0] == "wl-paste" and not os.environ.get("WAYLAND_DISPLAY"):
202
+ continue
203
+ data = await _read_cmd(cmd)
204
+ if data:
205
+ return data.decode(errors="replace")
206
+ return ""
207
+
208
+
209
+ async def clipboard_image_qr() -> list[str]:
210
+ """QR de una imagen copiada al portapapeles (p. ej. «copiar imagen» en el navegador)."""
211
+ cmds = []
212
+ if os.environ.get("WAYLAND_DISPLAY"):
213
+ cmds.append(["wl-paste", "-t", "image/png"])
214
+ if os.environ.get("DISPLAY"):
215
+ cmds.append(["xclip", "-selection", "clipboard", "-t", "image/png", "-o"])
216
+ for cmd in cmds:
217
+ data = await _read_cmd(cmd)
218
+ if not data:
219
+ continue
220
+ path = private_dir() / f"clip-{secrets.token_hex(6)}.png"
221
+ try:
222
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
223
+ with os.fdopen(fd, "wb") as f:
224
+ f.write(data)
225
+ return await asyncio.get_running_loop().run_in_executor(None, decode_qr, path)
226
+ except OSError:
227
+ continue
228
+ finally:
229
+ path.unlink(missing_ok=True)
230
+ return []