CLI for SidePulse
Python
Support development APNs tokens and unlink command
Peter Kuhar8a5b46f2da49
diff --git a/README.md b/README.mdindex 5d80e1e..ebdefa5 100644--- a/README.md+++ b/README.md@@ -146,12 +146,29 @@ The writer decodes simple escapes such as `\n`, then enforces the controller's### Link an iPhoneRun one command and either scan the terminal QR code with the SidePulse iOS app-or paste the 64-character push token shown by the app:+or paste the push token shown by the app. Production tokens have 64 hexadecimal+characters; development tokens have the `dev_` prefix followed by 64 hexadecimal+characters. Keep the prefix when pasting or saving a development token.```shsidepulse link```+List saved iPhones and remove a stale link by its displayed ID:++```sh+sidepulse unlink+sidepulse unlink ID_FROM_LIST+sidepulse link+```++`unlink` requires an exact ID. This keeps phones with the same name separate.+If two links have the same displayed ID, remove the intended entry by its full+token from `~/.config/sidepulse/agent-monitor/links.json` (or the equivalent+under `$XDG_CONFIG_HOME/sidepulse/agent-monitor/links.json`). Pair with the+updated iOS build by scanning the QR code or pasting its current push token.+Do not add or remove `dev_` by hand; the token determines the bridge route.+Linked phones are stored locally. Remote LED-only writes are silent. Adding`--title` or `--message` produces one visible notification containing the sameLED program and event metadata. Remote payloads also include the sendingdiff --git a/src/sidepulse/cli.py b/src/sidepulse/cli.pyindex d89709b..f53fe0c 100644--- a/src/sidepulse/cli.py+++ b/src/sidepulse/cli.py@@ -55,6 +55,7 @@ from .links import (new_pairing_channel,normalize_apns_token,pairing_url,+ remove_ios_link,render_terminal_qr,send_ios_program,store_ios_link,@@ -192,6 +193,13 @@ def build_sidepulse_parser() -> argparse.ArgumentParser:link.add_argument("relay_code", nargs="?", help="Relay code printed by the receiving Mac.")link.set_defaults(func=cmd_sidepulse_link)+ unlink = subparsers.add_parser(+ "unlink",+ help="List linked iPhones or remove one by its displayed ID.",+ )+ unlink.add_argument("link_id", nargs="?", help="Exact linked iPhone ID to remove.")+ unlink.set_defaults(func=cmd_sidepulse_unlink)+service = subparsers.add_parser("service",help="Manage the headless SidePulse background service.",@@ -780,6 +788,42 @@ def cmd_sidepulse_link(args: argparse.Namespace) -> int:return 0+def cmd_sidepulse_unlink(args: argparse.Namespace) -> int:+ links = load_ios_links()+ if args.link_id is None:+ if not links:+ print("No linked iPhones.")+ return 0+ print("Linked iPhones:")+ for link in links:+ print(f" {link.name} ({link.link_id})")+ print("Remove one with `sidepulse unlink ID_FROM_LIST`.")+ return 0++ matches = [link for link in links if link.link_id.casefold() == args.link_id.casefold()]+ if not matches:+ print(f"sidepulse unlink: No linked iPhone has ID {args.link_id!r}.", file=sys.stderr)+ return 1+ if len(matches) != 1:+ print(+ f"sidepulse unlink: ID {args.link_id!r} matches multiple links. "+ "Remove the intended entry from links.json by its full token.",+ file=sys.stderr,+ )+ return 1++ try:+ removed = remove_ios_link(matches[0].token)+ except OSError as exc:+ print(f"sidepulse unlink: Could not save the linked phones: {exc}", file=sys.stderr)+ return 1+ if removed is None:+ print("sidepulse unlink: The linked iPhone has already been removed.", file=sys.stderr)+ return 1+ print(f"Unlinked {removed.name} ({removed.link_id}).")+ return 0++def cmd_sidepulse_battery_status(args: argparse.Namespace) -> int:try:snapshot = read_battery_snapshot(full_charge_watts=full_watts_from_args(args))diff --git a/src/sidepulse/links.py b/src/sidepulse/links.pyindex 6038919..394af52 100644--- a/src/sidepulse/links.py+++ b/src/sidepulse/links.py@@ -23,7 +23,7 @@ from .settings import default_config_dirDEFAULT_BRIDGE_SERVER = "https://bridge.sidepulse.io"PAIRING_TIMEOUT_SECONDS = 5 * 60IOS_BUNDLE_ID = "io.sidepulse.ios"-APNS_TOKEN_PATTERN = re.compile(r"^[0-9a-fA-F]{64}$")+APNS_TOKEN_PATTERN = re.compile(r"(?:dev_)?[0-9a-f]{64}")PAIRING_CHANNEL_PATTERN = re.compile(r"^[A-Za-z0-9_-]{11}$")@@ -75,7 +75,9 @@ def normalize_server(value: str) -> str:def normalize_apns_token(value: str) -> str:token = "".join(value.split()).lower()if not APNS_TOKEN_PATTERN.fullmatch(token):- raise LinkError("Push token must be exactly 64 hexadecimal characters.")+ raise LinkError(+ "Push token must be 64 hexadecimal characters, optionally prefixed with 'dev_'."+ )return tokendiff --git a/tests/test_links.py b/tests/test_links.pyindex 82be1df..87c3eec 100644--- a/tests/test_links.py+++ b/tests/test_links.py@@ -6,6 +6,7 @@ import osimport sysimport tempfileimport unittest+import urllib.errorfrom pathlib import Pathfrom unittest.mock import MagicMock, patch@@ -35,16 +36,44 @@ from sidepulse.links import ( # noqa: E402TOKEN_A = "a" * 64TOKEN_B = "b" * 64+DEV_TOKEN_A = "dev_" + TOKEN_Aclass LinkStorageTests(unittest.TestCase):def test_token_is_normalized_and_validated(self) -> None:self.assertEqual(normalize_apns_token("AA " * 32), TOKEN_A)- for invalid in ("", "a" * 63, "g" * 64):+ self.assertEqual(normalize_apns_token(" DEV_" + "AA " * 32), DEV_TOKEN_A)+ for invalid in (+ "",+ "a" * 63,+ "g" * 64,+ "dev_",+ "dev_" + "a" * 63,+ "dev_dev_" + TOKEN_A,+ "test_" + TOKEN_A,+ "dev_" + "g" * 64,+ "dev_" + "a" * 65,+ ):with self.subTest(invalid=invalid):with self.assertRaises(LinkError):normalize_apns_token(invalid)+ def test_development_registration_response_keeps_prefix(self) -> None:+ response = json.dumps(+ {+ "v": 1,+ "type": "ios_registration",+ "device": {+ "name": "Peter's iPhone",+ "platform": "ios",+ "bundle_id": "io.sidepulse.ios",+ "push_token": DEV_TOKEN_A.upper(),+ },+ }+ )+ link = parse_ios_registration(response, server="https://bridge.sidepulse.io")+ self.assertEqual(link.token, DEV_TOKEN_A)+def test_links_round_trip_with_private_permissions(self) -> None:with tempfile.TemporaryDirectory() as temporary:path = Path(temporary) / "links.json"@@ -53,6 +82,36 @@ class LinkStorageTests(unittest.TestCase):self.assertEqual(load_ios_links(path), (link,))self.assertEqual(path.stat().st_mode & 0o777, 0o600)+ def test_links_round_trip_development_and_legacy_production_tokens(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ path = Path(temporary) / "links.json"+ # Version 1 files created before development tokens contain plain hex.+ path.write_text(+ json.dumps({"version": 1, "ios": [{"name": "Old iPhone", "token": TOKEN_A}]}),+ encoding="utf-8",+ )+ old_link = load_ios_links(path)[0]+ dev_link = IOSLink("Development iPhone", DEV_TOKEN_A)++ stored = store_ios_link(dev_link, path)++ self.assertEqual(stored, (old_link, dev_link))+ self.assertEqual(load_ios_links(path), (old_link, dev_link))+ payload = json.loads(path.read_text(encoding="utf-8"))+ self.assertEqual([item["token"] for item in payload["ios"]], [TOKEN_A, DEV_TOKEN_A])++ def test_production_and_development_tokens_are_distinct_destinations(self) -> None:+ production = IOSLink("iPhone", TOKEN_A)+ development = IOSLink("iPhone", DEV_TOKEN_A)+ self.assertNotEqual(production.link_id, development.link_id)++ with tempfile.TemporaryDirectory() as temporary:+ path = Path(temporary) / "links.json"+ self.assertEqual(store_ios_link(production, path), (production,))+ self.assertEqual(store_ios_link(development, path), (production, development))+ self.assertEqual(remove_ios_link(DEV_TOKEN_A, path), development)+ self.assertEqual(load_ios_links(path), (production,))+def test_relinking_a_token_updates_instead_of_duplicating(self) -> None:with tempfile.TemporaryDirectory() as temporary:path = Path(temporary) / "links.json"@@ -140,6 +199,48 @@ class LinkStorageTests(unittest.TestCase):self.assertEqual(link.token, TOKEN_B)+class UnlinkCLITests(unittest.TestCase):+ def test_unlink_lists_and_removes_only_exact_id_when_names_match(self) -> None:+ production = IOSLink("iPhone", TOKEN_A)+ development = IOSLink("iPhone", DEV_TOKEN_A)+ with tempfile.TemporaryDirectory() as temporary:+ path = Path(temporary) / "links.json"+ save_ios_links((production, development), path)+ with patch("sidepulse.links.default_links_path", return_value=path):+ stdout = io.StringIO()+ with patch("sys.stdout", stdout):+ self.assertEqual(sidepulse_main(["unlink"]), 0)+ self.assertIn(production.link_id, stdout.getvalue())+ self.assertIn(development.link_id, stdout.getvalue())++ stderr = io.StringIO()+ with patch("sys.stderr", stderr):+ self.assertEqual(sidepulse_main(["unlink", "iPhone"]), 1)+ self.assertEqual(load_ios_links(path), (production, development))++ stdout = io.StringIO()+ with patch("sys.stdout", stdout):+ self.assertEqual(sidepulse_main(["unlink", development.link_id]), 0)+ self.assertIn(development.link_id, stdout.getvalue())+ self.assertEqual(load_ios_links(path), (production,))++ def test_unlink_refuses_colliding_displayed_ids(self) -> None:+ first = IOSLink("iPhone", DEV_TOKEN_A)+ second = IOSLink("iPhone", "dev_" + "a" * 8 + "b" * 56)+ self.assertEqual(first.link_id, second.link_id)+ with tempfile.TemporaryDirectory() as temporary:+ path = Path(temporary) / "links.json"+ save_ios_links((first, second), path)+ stderr = io.StringIO()+ with (+ patch("sidepulse.links.default_links_path", return_value=path),+ patch("sys.stderr", stderr),+ ):+ self.assertEqual(sidepulse_main(["unlink", first.link_id]), 1)+ self.assertIn("matches multiple links", stderr.getvalue())+ self.assertEqual(load_ios_links(path), (first, second))++class WriteFallbackTests(unittest.TestCase):def test_write_requires_selection_when_multiple_linked_phones_exist(self) -> None:links = (IOSLink("Phone A", TOKEN_A), IOSLink("Phone B", TOKEN_B))@@ -257,6 +358,20 @@ class WriteFallbackTests(unittest.TestCase):self.assertEqual(result, 0)self.assertEqual(send.call_args.args[:2], (phones[1], "off"))+ def test_write_selects_production_and_development_destinations_separately(self) -> None:+ phones = (IOSLink("iPhone", TOKEN_A), IOSLink("iPhone", DEV_TOKEN_A))+ for phone in phones:+ with self.subTest(link_id=phone.link_id):+ with (+ patch("sidepulse.cli.discover_devices", return_value=[]),+ patch("sidepulse.cli.load_ios_links", return_value=phones),+ patch("sidepulse.cli._remote_event_data", return_value={}),+ patch("sidepulse.cli.send_ios_program", return_value="OK") as send,+ ):+ result = sidepulse_main(["write", "off", "--to", phone.link_id])+ self.assertEqual(result, 0)+ self.assertEqual(send.call_args.args[0], phone)+def test_notification_cannot_target_local_device(self) -> None:with tempfile.TemporaryDirectory() as temporary:root = Path(temporary) / "SidePulseDot"@@ -400,6 +515,41 @@ class IOSPayloadTests(unittest.TestCase):self.assertNotIn("title", payload)self.assertNotIn("body", payload)+ def test_outgoing_url_preserves_production_and_development_routing(self) -> None:+ response = MagicMock()+ response.__enter__.return_value.read.return_value = b"OK"+ for token, expected_url in (+ (TOKEN_A, f"https://bridge.sidepulse.io/api/leds/apns_{TOKEN_A}"),+ (DEV_TOKEN_A, f"https://bridge.sidepulse.io/api/leds/apns_dev_{TOKEN_A}"),+ ):+ with self.subTest(token_prefix=token[:4]), patch(+ "sidepulse.links.urllib.request.urlopen", return_value=response+ ) as open_url:+ send_ios_program(IOSLink("Phone", token), "off")+ self.assertEqual(open_url.call_args.args[0].full_url, expected_url)++ def test_apns_rejection_produces_failed_cli_result(self) -> None:+ phone = IOSLink("Development iPhone", DEV_TOKEN_A)+ stderr = io.StringIO()+ apns_error = urllib.error.HTTPError(+ "https://bridge.sidepulse.io/api/leds/apns_dev_" + TOKEN_A,+ 410,+ "Gone",+ {},+ io.BytesIO(b"APNs rejected token"),+ )+ with (+ patch("sidepulse.cli.discover_devices", return_value=[]),+ patch("sidepulse.cli.load_ios_links", return_value=(phone,)),+ patch("sidepulse.cli._remote_event_data", return_value={}),+ patch("sidepulse.links.urllib.request.urlopen", side_effect=apns_error),+ patch("sys.stderr", stderr),+ ):+ result = sidepulse_main(["write", "off", "--to", phone.link_id])++ self.assertEqual(result, 1)+ self.assertIn("APNs rejected token", stderr.getvalue())+if __name__ == "__main__":unittest.main()