Skip to content

CLI for SidePulse

Python

Open pairing QR as a crisp vector

Peter Kuhar13ed5042382d
diff --git a/src/sidepulse/cli.py b/src/sidepulse/cli.py
index 3b8af33..126e776 100644
--- a/src/sidepulse/cli.py
+++ b/src/sidepulse/cli.py
@@ -8,6 +8,7 @@ import select
import shutil
import subprocess
import sys
+import tempfile
import threading
import time
import uuid
@@ -51,6 +52,7 @@ from .links import (
new_pairing_channel,
normalize_apns_token,
pairing_url,
+ render_pairing_qr_page,
render_terminal_qr,
send_ios_program,
store_ios_link,
@@ -371,6 +373,7 @@ def cmd_sidepulse_link(_args: argparse.Namespace) -> int:
server = bridge_server()
channel = new_pairing_channel()
url = pairing_url(server, channel)
+ qr_page = render_pairing_qr_page(url)
qr = render_terminal_qr(
url,
ansi=sys.stdout.isatty()
@@ -392,16 +395,42 @@ def cmd_sidepulse_link(_args: argparse.Namespace) -> int:
)
listener.start()
+ pairing_page_path: Path | None = None
+ if sys.platform == "darwin" and sys.stdout.isatty() and "SSH_TTY" not in os.environ:
+ try:
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ encoding="utf-8",
+ prefix="sidepulse-link-",
+ suffix=".html",
+ delete=False,
+ ) as pairing_page:
+ pairing_page.write(qr_page)
+ pairing_page_path = Path(pairing_page.name)
+ subprocess.run(
+ ["open", str(pairing_page_path)],
+ check=True,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ except (OSError, subprocess.CalledProcessError):
+ if pairing_page_path is not None:
+ pairing_page_path.unlink(missing_ok=True)
+ pairing_page_path = None
+
existing = load_ios_links()
if existing:
print("Linked phones: " + ", ".join(link.name for link in existing))
print()
print("Link your iPhone")
print()
- print("Scan this QR code with your phone:")
- print()
- print(qr)
- print()
+ if pairing_page_path is not None:
+ print("Scan the QR code opened in your browser.")
+ else:
+ print("Scan this QR code with your phone:")
+ print()
+ print(qr)
+ print()
print("Or paste the push token shown in the SidePulse app.")
input_enabled = True
@@ -450,6 +479,8 @@ def cmd_sidepulse_link(_args: argparse.Namespace) -> int:
return 1
finally:
stop.set()
+ if pairing_page_path is not None:
+ pairing_page_path.unlink(missing_ok=True)
if prompt_visible:
print()
diff --git a/src/sidepulse/links.py b/src/sidepulse/links.py
index afc4a19..0356492 100644
--- a/src/sidepulse/links.py
+++ b/src/sidepulse/links.py
@@ -166,17 +166,21 @@ def pairing_url(server: str, channel: str, sender: str | None = None) -> str:
return "sidepulse://pair?" + urllib.parse.urlencode(query)
-def render_terminal_qr(value: str, *, ansi: bool = False) -> str:
+def _qr_matrix(value: str, *, border: int) -> list[list[bool]]:
try:
import qrcode
from qrcode.constants import ERROR_CORRECT_M
except ImportError as exc: # pragma: no cover - packaging installs it.
raise LinkError("QR support is unavailable; reinstall SidePulse and try again.") from exc
- code = qrcode.QRCode(version=None, error_correction=ERROR_CORRECT_M, box_size=1, border=2)
+ code = qrcode.QRCode(version=None, error_correction=ERROR_CORRECT_M, box_size=1, border=border)
code.add_data(value)
code.make(fit=True)
- matrix = code.get_matrix()
+ return code.get_matrix()
+
+
+def render_terminal_qr(value: str, *, ansi: bool = False) -> str:
+ matrix = _qr_matrix(value, border=2)
pixels = {
(False, False): " ",
(True, False): "▀",
@@ -211,6 +215,67 @@ def render_terminal_qr(value: str, *, ansi: bool = False) -> str:
return "\n".join(lines)
+def render_pairing_qr_page(value: str) -> str:
+ matrix = _qr_matrix(value, border=4)
+ size = len(matrix)
+ path_parts: list[str] = []
+ for row_index, row in enumerate(matrix):
+ column = 0
+ while column < size:
+ if not row[column]:
+ column += 1
+ continue
+ run_start = column
+ while column < size and row[column]:
+ column += 1
+ path_parts.append(
+ f"M{run_start} {row_index}h{column - run_start}v1H{run_start}z"
+ )
+ qr_pixels = size * 12
+ qr_path = "".join(path_parts)
+ return f"""<!doctype html>
+<html lang="en">
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Link SidePulse</title>
+<style>
+ * {{ box-sizing: border-box; }}
+ body {{
+ margin: 0;
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ background: #f5f5f7;
+ color: #1d1d1f;
+ font-family: -apple-system, BlinkMacSystemFont, sans-serif;
+ }}
+ main {{
+ width: min(92vw, 500px);
+ padding: 28px;
+ border: 1px solid #dedee3;
+ border-radius: 24px;
+ background: white;
+ box-shadow: 0 16px 48px rgb(0 0 0 / 10%);
+ text-align: center;
+ }}
+ h1 {{ margin: 0 0 6px; font-size: 24px; letter-spacing: -0.02em; }}
+ p {{ margin: 0 0 20px; color: #6e6e73; font-size: 15px; }}
+ svg {{ display: block; width: 100%; height: auto; }}
+</style>
+<main>
+ <h1>Link your iPhone</h1>
+ <p>Scan with your iPhone Camera.</p>
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {size} {size}"
+ width="{qr_pixels}" height="{qr_pixels}" shape-rendering="crispEdges"
+ role="img" aria-label="SidePulse pairing QR code">
+ <rect width="{size}" height="{size}" fill="#fff"/>
+ <path d="{qr_path}" fill="#000"/>
+ </svg>
+</main>
+</html>
+"""
+
+
def parse_ios_registration(value: str, *, server: str) -> IOSLink:
try:
payload = json.loads(value)
diff --git a/tests/test_links.py b/tests/test_links.py
index 15dd14a..e10191d 100644
--- a/tests/test_links.py
+++ b/tests/test_links.py
@@ -25,6 +25,7 @@ from sidepulse.links import ( # noqa: E402
normalize_apns_token,
pairing_url,
parse_ios_registration,
+ render_pairing_qr_page,
render_terminal_qr,
save_ios_links,
store_ios_link,
@@ -97,6 +98,13 @@ class LinkStorageTests(unittest.TestCase):
self.assertIn("\033[40m", rendered)
self.assertTrue(all(line.endswith("\033[0m") for line in rendered.splitlines()))
+ def test_pairing_qr_page_is_vector_and_does_not_expose_the_link(self) -> None:
+ rendered = render_pairing_qr_page("sidepulse://p/7kP2_xQ9mLs")
+ self.assertIn("<svg", rendered)
+ self.assertIn('shape-rendering="crispEdges"', rendered)
+ self.assertIn("<path", rendered)
+ self.assertNotIn("sidepulse://", rendered)
+
def test_sse_parser_returns_complete_data_events(self) -> None:
response = iter(
[