chronim 0.1.0__tar.gz

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.
chronim-0.1.0/LICENSE ADDED
@@ -0,0 +1,17 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chronim contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
chronim-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,182 @@
1
+ Metadata-Version: 2.4
2
+ Name: chronim
3
+ Version: 0.1.0
4
+ Summary: Control Google Chrome directly from Python through a local extension bridge.
5
+ Author: Dima
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: websockets<16,>=12
14
+ Dynamic: license-file
15
+
16
+ # Chronim
17
+
18
+ **Control your browser. Directly from Python.** Chronim connects Python to Chrome through a Manifest V3 extension and an authenticated WebSocket server bound to localhost. It does not use Selenium, Playwright, or Puppeteer.
19
+
20
+ > The source project is implemented here. Actual browser operations require installing the extension and having Chrome connected. This environment does not have a confirmed live Chrome session, so the examples below are not represented as end-to-end browser tested.
21
+
22
+ ## What it does
23
+
24
+ - Open, navigate, inspect, and close Chrome tabs.
25
+ - Click and inspect DOM elements by CSS selector, type into fields, and wait for elements.
26
+ - Send DOM keyboard and pointer events, take a visible-tab screenshot, and run JavaScript in the active page's main world.
27
+ - Use a synchronous API or an `asyncio` API over the same JSON request/response protocol.
28
+ - Authenticate Python and the extension with a random per-user key; bind the bridge to `127.0.0.1` by default.
29
+
30
+ The main flow is:
31
+
32
+ ```text
33
+ Python Browser API ──WebSocket──> Local Bridge ──WebSocket──> MV3 extension ──Chrome APIs/DOM──> Chrome
34
+ ```
35
+
36
+ The bridge multiplexes responses by request ID, validates JSON messages, restricts incoming peers to loopback, checks browser extension origins, and sends only supported action names to the extension. It does not expose OS command execution or filesystem access. Page actions are limited by Chrome's extension and page security restrictions. DOM keyboard/mouse methods dispatch browser events; they do not emulate physical hardware input.
37
+
38
+ ## Install
39
+
40
+ From this directory, install the package and dependency:
41
+
42
+ ```bash
43
+ python -m pip install .
44
+ ```
45
+
46
+ Python 3.10+ is required. The first `chronim.connect()` creates a random key in the current user's config directory (`%APPDATA%/chronim/config.json` on Windows, `~/.config/chronim/config.json` elsewhere) and starts the local bridge on `127.0.0.1:8765`. The config file is created with owner-only permissions where supported. Alternatively, set `CHRONIM_API_KEY` to a key of at least 32 characters; `chronim.generate_api_key()` creates a suitable key.
47
+
48
+ ## Install the Chrome extension
49
+
50
+ 1. Open `chrome://extensions` in Chrome and enable **Developer mode**.
51
+ 2. Choose **Load unpacked** and select this project's `extension/` folder.
52
+ 3. Start a Python script that calls `chronim.connect()` (this starts the bridge).
53
+ 4. Click the Chronim toolbar icon. In Python, print your key with:
54
+
55
+ ```bash
56
+ python -c "import chronim; print(chronim.get_api_key())"
57
+ ```
58
+
59
+ 5. Paste that key into the extension popup and choose **Save key and connect**. The popup should show **Connected**.
60
+
61
+ The key is stored in Chrome extension local storage and the per-user Chronim config. Do not share either. To change keys, set `CHRONIM_API_KEY` in the Python process and update the popup to the same value. The extension reconnects automatically when the local bridge becomes available. Use the popup's Save action after starting the Python process if the extension was loaded before the bridge.
62
+
63
+ The extension requests `tabs`, `activeTab`, `scripting`, and `storage`; host access to HTTP(S) pages is used to perform DOM actions across tabs. Chrome internal pages, the Chrome Web Store, and pages that block extension scripting cannot be automated.
64
+
65
+ ## First program
66
+
67
+ ```python
68
+ import chronim
69
+
70
+ browser = chronim.connect()
71
+ try:
72
+ browser.open("https://example.com")
73
+ browser.wait_for_load()
74
+ print(browser.title())
75
+ print(browser.url())
76
+ finally:
77
+ browser.disconnect()
78
+ ```
79
+
80
+ Use `browser.close()` to close the active Chrome tab and disconnect the Python client. Use `disconnect()` when you only want to close the Python connection.
81
+
82
+ ## Examples
83
+
84
+ See [`examples/basic.py`](examples/basic.py), [`examples/google_search.py`](examples/google_search.py), [`examples/tabs.py`](examples/tabs.py), and [`examples/async_example.py`](examples/async_example.py).
85
+
86
+ ```python
87
+ import chronim
88
+
89
+ browser = chronim.connect()
90
+ browser.open("https://www.google.com")
91
+ browser.wait_for_load()
92
+ browser.type("textarea[name=q]", "Chronim")
93
+ browser.press("ENTER")
94
+ browser.wait_for_load()
95
+ print(browser.title())
96
+ browser.disconnect()
97
+ ```
98
+
99
+ Async version:
100
+
101
+ ```python
102
+ import asyncio
103
+ import chronim
104
+
105
+ async def main():
106
+ browser = await chronim.connect_async()
107
+ try:
108
+ await browser.open("https://example.com")
109
+ await browser.wait_for_load()
110
+ print(await browser.title())
111
+ finally:
112
+ await browser.disconnect()
113
+
114
+ asyncio.run(main())
115
+ ```
116
+
117
+ ## API reference
118
+
119
+ `chronim.connect(*, api_key=None, host="127.0.0.1", port=8765, timeout=15)` returns a synchronous `Browser`. `await chronim.connect_async(...)` returns an `AsyncBrowser`. The async API exposes the same browser, element, keyboard, mouse, and tab methods with `await`.
120
+
121
+ | Methods | Arguments / result |
122
+ |---|---|
123
+ | `open(url)`, `back()`, `forward()`, `refresh()`, `close()`, `disconnect()` | Navigate or close a tab/client; navigation calls return operation results. `close()` closes active tab and disconnects; `disconnect()` only disconnects the client. |
124
+ | `title()`, `url()` | Return active tab title and URL strings. |
125
+ | `screenshot()` | Return Chrome's PNG data URL for the visible tab. |
126
+ | `execute_js(code)` | Evaluate JavaScript in the active page's main world and return its serializable result. It has no Node.js or OS APIs. Chrome applies that page's Content Security Policy, so pages that disallow dynamic evaluation may reject the operation. |
127
+ | `wait_for_load(timeout=30)`, `sleep(seconds)` | Wait for active tab load completion or for a bounded delay. |
128
+ | `click(selector)`, `type(selector, text)`, `clear(selector)` | Click or edit the first matching CSS element. `type` replaces the input value and dispatches input/change events. |
129
+ | `get_text(selector)`, `get_attribute(selector, attribute)`, `get_html(selector)` | Return text, an attribute (or `None`), or inner HTML. |
130
+ | `find(selector)`, `find_all(selector)`, `exists(selector)` | Return element description(s), or a boolean. Descriptions include tag, id, classes, short text, and attributes. |
131
+ | `wait_for_element(selector, timeout=10)` | Poll for an element and return its description. |
132
+ | `press(key)`, `hotkey(*keys)` | Dispatch DOM keyboard events, e.g. `press("ENTER")` or `hotkey("CTRL", "A")`. |
133
+ | `scroll(x=0, y=0)`, `move(x, y)` | Scroll by pixel offsets or dispatch a pointer move at viewport coordinates. |
134
+ | `new_tab(url=None)`, `close_tab(tab_id)`, `switch_tab(tab_id)` | Create, close, or activate a tab. Creation and switching return tab information. |
135
+ | `get_tabs()`, `active_tab()` | Return tab metadata dictionaries. |
136
+
137
+ `get_api_key()` reads/creates the local key. `generate_api_key()` returns a secure random key for use as `CHRONIM_API_KEY`.
138
+
139
+ ## Errors
140
+
141
+ All library errors inherit from `ChronimError`:
142
+
143
+ - `ConnectionError`: the local bridge is unavailable or disconnected.
144
+ - `AuthenticationError`: the key was rejected.
145
+ - `ExtensionNotFoundError`: the extension is not connected to the bridge.
146
+ - `ElementNotFoundError`: a selector has no matching element.
147
+ - `TimeoutError`: a command or wait expired.
148
+ - `BrowserError`: Chrome or the page rejected an operation.
149
+ - `ProtocolError`: the message was malformed or unsupported.
150
+
151
+ ```python
152
+ import chronim
153
+
154
+ try:
155
+ browser = chronim.connect()
156
+ print(browser.get_text("h1"))
157
+ except chronim.ExtensionNotFoundError as exc:
158
+ print(f"Open the Chronim extension popup and connect it: {exc}")
159
+ finally:
160
+ if "browser" in locals():
161
+ browser.disconnect()
162
+ ```
163
+
164
+ ## Troubleshooting
165
+
166
+ - **Popup says disconnected:** start the Python process first, check that it listens on port 8765, then save/connect the key again.
167
+ - **Authentication failed:** compare the extension key with `chronim.get_api_key()` in the same environment as the script. An environment key overrides the local config.
168
+ - **Address already in use:** another Chronim process may own port 8765. Stop that process or choose a custom port consistently for Python and the popup.
169
+ - **Element not found:** wait for page load, verify the CSS selector in DevTools, and make sure the target is not inside a cross-origin iframe.
170
+ - **Chrome page cannot be scripted:** Chrome internal pages, store pages, and certain restricted frames disallow content scripts.
171
+ - **Screenshot unavailable:** Chrome may reject capture for a restricted or protected tab.
172
+ - **No physical keyboard/mouse behavior:** Chronim emits DOM events. Sites may ignore synthetic events where trusted user input is required.
173
+
174
+ ## Development checks
175
+
176
+ Run the included standard-library tests with:
177
+
178
+ ```bash
179
+ python -m unittest discover -s tests -v
180
+ ```
181
+
182
+ Those tests cover the protocol and Python API surface without requiring a live Chrome session. A real-browser smoke test still requires installing the extension and connecting Chrome as described above.
@@ -0,0 +1,167 @@
1
+ # Chronim
2
+
3
+ **Control your browser. Directly from Python.** Chronim connects Python to Chrome through a Manifest V3 extension and an authenticated WebSocket server bound to localhost. It does not use Selenium, Playwright, or Puppeteer.
4
+
5
+ > The source project is implemented here. Actual browser operations require installing the extension and having Chrome connected. This environment does not have a confirmed live Chrome session, so the examples below are not represented as end-to-end browser tested.
6
+
7
+ ## What it does
8
+
9
+ - Open, navigate, inspect, and close Chrome tabs.
10
+ - Click and inspect DOM elements by CSS selector, type into fields, and wait for elements.
11
+ - Send DOM keyboard and pointer events, take a visible-tab screenshot, and run JavaScript in the active page's main world.
12
+ - Use a synchronous API or an `asyncio` API over the same JSON request/response protocol.
13
+ - Authenticate Python and the extension with a random per-user key; bind the bridge to `127.0.0.1` by default.
14
+
15
+ The main flow is:
16
+
17
+ ```text
18
+ Python Browser API ──WebSocket──> Local Bridge ──WebSocket──> MV3 extension ──Chrome APIs/DOM──> Chrome
19
+ ```
20
+
21
+ The bridge multiplexes responses by request ID, validates JSON messages, restricts incoming peers to loopback, checks browser extension origins, and sends only supported action names to the extension. It does not expose OS command execution or filesystem access. Page actions are limited by Chrome's extension and page security restrictions. DOM keyboard/mouse methods dispatch browser events; they do not emulate physical hardware input.
22
+
23
+ ## Install
24
+
25
+ From this directory, install the package and dependency:
26
+
27
+ ```bash
28
+ python -m pip install .
29
+ ```
30
+
31
+ Python 3.10+ is required. The first `chronim.connect()` creates a random key in the current user's config directory (`%APPDATA%/chronim/config.json` on Windows, `~/.config/chronim/config.json` elsewhere) and starts the local bridge on `127.0.0.1:8765`. The config file is created with owner-only permissions where supported. Alternatively, set `CHRONIM_API_KEY` to a key of at least 32 characters; `chronim.generate_api_key()` creates a suitable key.
32
+
33
+ ## Install the Chrome extension
34
+
35
+ 1. Open `chrome://extensions` in Chrome and enable **Developer mode**.
36
+ 2. Choose **Load unpacked** and select this project's `extension/` folder.
37
+ 3. Start a Python script that calls `chronim.connect()` (this starts the bridge).
38
+ 4. Click the Chronim toolbar icon. In Python, print your key with:
39
+
40
+ ```bash
41
+ python -c "import chronim; print(chronim.get_api_key())"
42
+ ```
43
+
44
+ 5. Paste that key into the extension popup and choose **Save key and connect**. The popup should show **Connected**.
45
+
46
+ The key is stored in Chrome extension local storage and the per-user Chronim config. Do not share either. To change keys, set `CHRONIM_API_KEY` in the Python process and update the popup to the same value. The extension reconnects automatically when the local bridge becomes available. Use the popup's Save action after starting the Python process if the extension was loaded before the bridge.
47
+
48
+ The extension requests `tabs`, `activeTab`, `scripting`, and `storage`; host access to HTTP(S) pages is used to perform DOM actions across tabs. Chrome internal pages, the Chrome Web Store, and pages that block extension scripting cannot be automated.
49
+
50
+ ## First program
51
+
52
+ ```python
53
+ import chronim
54
+
55
+ browser = chronim.connect()
56
+ try:
57
+ browser.open("https://example.com")
58
+ browser.wait_for_load()
59
+ print(browser.title())
60
+ print(browser.url())
61
+ finally:
62
+ browser.disconnect()
63
+ ```
64
+
65
+ Use `browser.close()` to close the active Chrome tab and disconnect the Python client. Use `disconnect()` when you only want to close the Python connection.
66
+
67
+ ## Examples
68
+
69
+ See [`examples/basic.py`](examples/basic.py), [`examples/google_search.py`](examples/google_search.py), [`examples/tabs.py`](examples/tabs.py), and [`examples/async_example.py`](examples/async_example.py).
70
+
71
+ ```python
72
+ import chronim
73
+
74
+ browser = chronim.connect()
75
+ browser.open("https://www.google.com")
76
+ browser.wait_for_load()
77
+ browser.type("textarea[name=q]", "Chronim")
78
+ browser.press("ENTER")
79
+ browser.wait_for_load()
80
+ print(browser.title())
81
+ browser.disconnect()
82
+ ```
83
+
84
+ Async version:
85
+
86
+ ```python
87
+ import asyncio
88
+ import chronim
89
+
90
+ async def main():
91
+ browser = await chronim.connect_async()
92
+ try:
93
+ await browser.open("https://example.com")
94
+ await browser.wait_for_load()
95
+ print(await browser.title())
96
+ finally:
97
+ await browser.disconnect()
98
+
99
+ asyncio.run(main())
100
+ ```
101
+
102
+ ## API reference
103
+
104
+ `chronim.connect(*, api_key=None, host="127.0.0.1", port=8765, timeout=15)` returns a synchronous `Browser`. `await chronim.connect_async(...)` returns an `AsyncBrowser`. The async API exposes the same browser, element, keyboard, mouse, and tab methods with `await`.
105
+
106
+ | Methods | Arguments / result |
107
+ |---|---|
108
+ | `open(url)`, `back()`, `forward()`, `refresh()`, `close()`, `disconnect()` | Navigate or close a tab/client; navigation calls return operation results. `close()` closes active tab and disconnects; `disconnect()` only disconnects the client. |
109
+ | `title()`, `url()` | Return active tab title and URL strings. |
110
+ | `screenshot()` | Return Chrome's PNG data URL for the visible tab. |
111
+ | `execute_js(code)` | Evaluate JavaScript in the active page's main world and return its serializable result. It has no Node.js or OS APIs. Chrome applies that page's Content Security Policy, so pages that disallow dynamic evaluation may reject the operation. |
112
+ | `wait_for_load(timeout=30)`, `sleep(seconds)` | Wait for active tab load completion or for a bounded delay. |
113
+ | `click(selector)`, `type(selector, text)`, `clear(selector)` | Click or edit the first matching CSS element. `type` replaces the input value and dispatches input/change events. |
114
+ | `get_text(selector)`, `get_attribute(selector, attribute)`, `get_html(selector)` | Return text, an attribute (or `None`), or inner HTML. |
115
+ | `find(selector)`, `find_all(selector)`, `exists(selector)` | Return element description(s), or a boolean. Descriptions include tag, id, classes, short text, and attributes. |
116
+ | `wait_for_element(selector, timeout=10)` | Poll for an element and return its description. |
117
+ | `press(key)`, `hotkey(*keys)` | Dispatch DOM keyboard events, e.g. `press("ENTER")` or `hotkey("CTRL", "A")`. |
118
+ | `scroll(x=0, y=0)`, `move(x, y)` | Scroll by pixel offsets or dispatch a pointer move at viewport coordinates. |
119
+ | `new_tab(url=None)`, `close_tab(tab_id)`, `switch_tab(tab_id)` | Create, close, or activate a tab. Creation and switching return tab information. |
120
+ | `get_tabs()`, `active_tab()` | Return tab metadata dictionaries. |
121
+
122
+ `get_api_key()` reads/creates the local key. `generate_api_key()` returns a secure random key for use as `CHRONIM_API_KEY`.
123
+
124
+ ## Errors
125
+
126
+ All library errors inherit from `ChronimError`:
127
+
128
+ - `ConnectionError`: the local bridge is unavailable or disconnected.
129
+ - `AuthenticationError`: the key was rejected.
130
+ - `ExtensionNotFoundError`: the extension is not connected to the bridge.
131
+ - `ElementNotFoundError`: a selector has no matching element.
132
+ - `TimeoutError`: a command or wait expired.
133
+ - `BrowserError`: Chrome or the page rejected an operation.
134
+ - `ProtocolError`: the message was malformed or unsupported.
135
+
136
+ ```python
137
+ import chronim
138
+
139
+ try:
140
+ browser = chronim.connect()
141
+ print(browser.get_text("h1"))
142
+ except chronim.ExtensionNotFoundError as exc:
143
+ print(f"Open the Chronim extension popup and connect it: {exc}")
144
+ finally:
145
+ if "browser" in locals():
146
+ browser.disconnect()
147
+ ```
148
+
149
+ ## Troubleshooting
150
+
151
+ - **Popup says disconnected:** start the Python process first, check that it listens on port 8765, then save/connect the key again.
152
+ - **Authentication failed:** compare the extension key with `chronim.get_api_key()` in the same environment as the script. An environment key overrides the local config.
153
+ - **Address already in use:** another Chronim process may own port 8765. Stop that process or choose a custom port consistently for Python and the popup.
154
+ - **Element not found:** wait for page load, verify the CSS selector in DevTools, and make sure the target is not inside a cross-origin iframe.
155
+ - **Chrome page cannot be scripted:** Chrome internal pages, store pages, and certain restricted frames disallow content scripts.
156
+ - **Screenshot unavailable:** Chrome may reject capture for a restricted or protected tab.
157
+ - **No physical keyboard/mouse behavior:** Chronim emits DOM events. Sites may ignore synthetic events where trusted user input is required.
158
+
159
+ ## Development checks
160
+
161
+ Run the included standard-library tests with:
162
+
163
+ ```bash
164
+ python -m unittest discover -s tests -v
165
+ ```
166
+
167
+ Those tests cover the protocol and Python API surface without requiring a live Chrome session. A real-browser smoke test still requires installing the extension and connecting Chrome as described above.
@@ -0,0 +1,24 @@
1
+ """Chronim: Control your browser. Directly from Python."""
2
+ from .browser import Browser, AsyncBrowser
3
+ from .bridge import ensure_sync_bridge
4
+ from .config import get_api_key, generate_api_key, DEFAULT_HOST, DEFAULT_PORT
5
+ from .connection import AsyncConnection, SyncConnection
6
+ from .exceptions import (ChronimError, ConnectionError, AuthenticationError, ElementNotFoundError,
7
+ TimeoutError, BrowserError, ProtocolError, ExtensionNotFoundError)
8
+
9
+ __version__ = "0.1.0"
10
+
11
+ def connect(*, api_key=None, host=DEFAULT_HOST, port=DEFAULT_PORT, timeout=15) -> Browser:
12
+ """Start/use the localhost bridge and connect a synchronous Browser client."""
13
+ key = api_key or get_api_key()
14
+ ensure_sync_bridge(key, host, port)
15
+ return Browser(SyncConnection(key, host, port, timeout))
16
+
17
+ async def connect_async(*, api_key=None, host=DEFAULT_HOST, port=DEFAULT_PORT, timeout=15) -> AsyncBrowser:
18
+ """Start/use the localhost bridge and connect an asynchronous Browser client."""
19
+ from .browser import create_async_browser
20
+ return await create_async_browser(api_key or get_api_key(), host, port, timeout)
21
+
22
+ __all__ = ["connect", "connect_async", "Browser", "AsyncBrowser", "get_api_key", "generate_api_key",
23
+ "ChronimError", "ConnectionError", "AuthenticationError", "ElementNotFoundError", "TimeoutError",
24
+ "BrowserError", "ProtocolError", "ExtensionNotFoundError", "__version__"]
@@ -0,0 +1,154 @@
1
+ """Authenticated localhost WebSocket server that routes requests to the extension."""
2
+ from __future__ import annotations
3
+ import asyncio, hmac, logging, re, threading
4
+ from typing import Any
5
+ import websockets
6
+ from websockets.exceptions import ConnectionClosed
7
+ from .config import DEFAULT_HOST, DEFAULT_PORT
8
+ from .exceptions import (AuthenticationError, BrowserError, ElementNotFoundError,
9
+ ExtensionNotFoundError, ProtocolError, TimeoutError)
10
+ from .protocol import dumps, loads, validate_request
11
+
12
+ logger = logging.getLogger("chronim")
13
+ _ALLOWED_ROLES = {"extension", "client"}
14
+
15
+ class Bridge:
16
+ def __init__(self, api_key: str, host: str = DEFAULT_HOST, port: int = DEFAULT_PORT, request_timeout: float = 30):
17
+ self.api_key, self.host, self.port, self.request_timeout = api_key, host, port, request_timeout
18
+ self._extension = None
19
+ self._pending: dict[str, asyncio.Future] = {}
20
+ self._server = None
21
+ self._lock = asyncio.Lock()
22
+
23
+ async def start(self):
24
+ try:
25
+ self._server = await websockets.serve(self._handler, self.host, self.port, max_size=16*1024*1024, ping_interval=20, ping_timeout=20)
26
+ except OSError as exc:
27
+ raise RuntimeError(f"Could not start Chronim bridge at {self.host}:{self.port}: {exc}") from exc
28
+
29
+ async def close(self):
30
+ if self._server:
31
+ self._server.close()
32
+ await self._server.wait_closed()
33
+ self._server = None
34
+ if self._extension:
35
+ await self._extension.close()
36
+
37
+ async def _handler(self, ws):
38
+ remote = ws.remote_address
39
+ if not remote or remote[0] not in ("127.0.0.1", "::1", "::ffff:127.0.0.1"):
40
+ await ws.close(code=1008, reason="localhost only")
41
+ return
42
+ headers = getattr(ws, "request_headers", None)
43
+ if headers is None:
44
+ headers = ws.request.headers
45
+ origin = headers.get("Origin", "")
46
+ if origin and not re.fullmatch(r"chrome-extension://[a-p]{32}", origin):
47
+ await ws.close(code=1008, reason="invalid origin")
48
+ return
49
+ try:
50
+ hello = loads(await asyncio.wait_for(ws.recv(), 5))
51
+ role = hello.get("role")
52
+ supplied = hello.get("token")
53
+ if role not in _ALLOWED_ROLES or not isinstance(supplied, str) or not hmac.compare_digest(supplied, self.api_key):
54
+ await ws.send(dumps({"type":"auth","success":False,"error":{"code":"AUTHENTICATION_FAILED","message":"Invalid Chronim API key"}}))
55
+ await ws.close(code=1008, reason="authentication failed")
56
+ return
57
+ await ws.send(dumps({"type":"auth","success":True,"role":role}))
58
+ if role == "extension":
59
+ await self._extension_loop(ws)
60
+ else:
61
+ await self._client_loop(ws)
62
+ except (asyncio.TimeoutError, ProtocolError, ConnectionClosed):
63
+ await ws.close(code=1002, reason="invalid handshake or protocol")
64
+
65
+ async def _extension_loop(self, ws):
66
+ old = self._extension
67
+ self._extension = ws
68
+ if old and old != ws:
69
+ await old.close()
70
+ logger.info("Chronim extension connected")
71
+ try:
72
+ async for raw in ws:
73
+ msg = loads(raw)
74
+ if msg.get("type") == "response" and isinstance(msg.get("id"), str):
75
+ future = self._pending.get(msg["id"])
76
+ if future and not future.done(): future.set_result(msg)
77
+ finally:
78
+ if self._extension is ws: self._extension = None
79
+ for future in self._pending.values():
80
+ if not future.done(): future.set_exception(ExtensionNotFoundError("Chronim extension disconnected"))
81
+ logger.info("Chronim extension disconnected")
82
+
83
+ async def _client_loop(self, ws):
84
+ async for raw in ws:
85
+ msg = {}
86
+ try:
87
+ msg = loads(raw); validate_request(msg)
88
+ result = await self.dispatch(msg["action"], msg.get("payload", {}), msg["id"])
89
+ response = {"type":"response","id":msg["id"],"success":True,"result":result}
90
+ except Exception as exc:
91
+ response = {"type":"response","id":msg.get("id", ""),"success":False,"error":{"code":getattr(exc,"code","BROWSER_ERROR"),"message":str(exc)}}
92
+ await ws.send(dumps(response))
93
+
94
+ async def dispatch(self, action: str, payload: dict[str, Any], request_id: str | None = None):
95
+ if not self._extension:
96
+ raise ExtensionNotFoundError("Chronim extension is not connected. Open the extension popup and connect it.")
97
+ rid = request_id or __import__("uuid").uuid4().hex
98
+ future = asyncio.get_running_loop().create_future()
99
+ self._pending[rid] = future
100
+ try:
101
+ await self._extension.send(dumps({"type":"request","id":rid,"action":action,"payload":payload}))
102
+ try: response = await asyncio.wait_for(future, self.request_timeout)
103
+ except asyncio.TimeoutError as exc: raise TimeoutError(f"Timed out waiting for {action} after {self.request_timeout:g}s") from exc
104
+ if not response.get("success"):
105
+ err = response.get("error") or {}
106
+ message = err.get("message", "Chrome command failed")
107
+ code = err.get("code")
108
+ if code == "PROTOCOL_ERROR": raise ProtocolError(message)
109
+ if code == "ELEMENT_NOT_FOUND": raise ElementNotFoundError(message)
110
+ if code == "TIMEOUT": raise TimeoutError(message)
111
+ raise BrowserError(message)
112
+ return response.get("result")
113
+ finally:
114
+ self._pending.pop(rid, None)
115
+
116
+ class _BridgeThread:
117
+ """Own a bridge in a daemon event-loop thread for the synchronous API."""
118
+ def __init__(self, api_key: str, host: str, port: int):
119
+ self.loop = asyncio.new_event_loop(); self.bridge = Bridge(api_key, host, port)
120
+ self.ready = threading.Event(); self.error = None
121
+ self.thread = threading.Thread(target=self._run, name="chronim-bridge", daemon=True)
122
+ self.thread.start()
123
+ self.loop.call_soon_threadsafe(self._start)
124
+ if not self.ready.wait(5): raise RuntimeError("Chronim bridge startup timed out")
125
+ if self.error: raise self.error
126
+ def _run(self):
127
+ asyncio.set_event_loop(self.loop); self.loop.run_forever()
128
+ def _start(self):
129
+ task = self.loop.create_task(self.bridge.start())
130
+ task.add_done_callback(self._started)
131
+ def _started(self, task):
132
+ try: task.result()
133
+ except Exception as exc: self.error = exc
134
+ self.ready.set()
135
+
136
+ _sync_lock = threading.Lock()
137
+ _sync_bridge: _BridgeThread | None = None
138
+ _async_bridges: dict[tuple[str,int,str], Bridge] = {}
139
+
140
+ def ensure_sync_bridge(api_key: str, host: str = DEFAULT_HOST, port: int = DEFAULT_PORT):
141
+ global _sync_bridge
142
+ with _sync_lock:
143
+ if _sync_bridge is not None:
144
+ bridge = _sync_bridge.bridge
145
+ if (bridge.api_key, bridge.host, bridge.port) != (api_key, host, port):
146
+ raise RuntimeError("A Chronim bridge is already running with a different key or port")
147
+ return
148
+ if _sync_bridge is None:
149
+ _sync_bridge = _BridgeThread(api_key, host, port)
150
+
151
+ async def ensure_async_bridge(api_key: str, host: str = DEFAULT_HOST, port: int = DEFAULT_PORT):
152
+ # Keep the listener alive beyond the caller's event loop (including asyncio.run()).
153
+ ensure_sync_bridge(api_key, host, port)
154
+ return _sync_bridge.bridge
@@ -0,0 +1,71 @@
1
+ """Synchronous and asynchronous browser APIs."""
2
+ from __future__ import annotations
3
+ import asyncio
4
+ from .elements import Elements
5
+ from .keyboard import Keyboard
6
+ from .mouse import Mouse
7
+ from .tabs import Tabs
8
+ from .screenshot import Screenshot
9
+ from .connection import SyncConnection, AsyncConnection
10
+
11
+ class Browser(Elements, Keyboard, Mouse, Tabs, Screenshot):
12
+ def __init__(self, connection): self._connection = connection
13
+ def _request(self, action, payload=None): return self._connection.request(action, payload)
14
+ def open(self, url): return self._request("browser.open", {"url": url})
15
+ def back(self): return self._request("browser.back")
16
+ def forward(self): return self._request("browser.forward")
17
+ def refresh(self): return self._request("browser.refresh")
18
+ def close(self):
19
+ try: return self._request("browser.close")
20
+ finally: self.disconnect()
21
+ def disconnect(self): self._connection.close()
22
+ def title(self): return self._request("browser.title")
23
+ def url(self): return self._request("browser.url")
24
+ def execute_js(self, code): return self._request("browser.execute_js", {"code": code})
25
+ def wait_for_load(self, timeout=30): return self._request("browser.wait_for_load", {"timeout": timeout})
26
+ def sleep(self, seconds):
27
+ if seconds < 0: raise ValueError("seconds must be non-negative")
28
+ return self._request("browser.sleep", {"seconds": seconds})
29
+
30
+ class AsyncBrowser:
31
+ def __init__(self, connection): self._connection = connection
32
+ async def _request(self, action, payload=None): return await self._connection.request(action, payload)
33
+ async def open(self, url): return await self._request("browser.open", {"url":url})
34
+ async def back(self): return await self._request("browser.back")
35
+ async def forward(self): return await self._request("browser.forward")
36
+ async def refresh(self): return await self._request("browser.refresh")
37
+ async def close(self):
38
+ try: return await self._request("browser.close")
39
+ finally: await self.disconnect()
40
+ async def disconnect(self): await self._connection.close()
41
+ async def title(self): return await self._request("browser.title")
42
+ async def url(self): return await self._request("browser.url")
43
+ async def screenshot(self): return await self._request("browser.screenshot")
44
+ async def execute_js(self, code): return await self._request("browser.execute_js", {"code":code})
45
+ async def wait_for_load(self, timeout=30): return await self._request("browser.wait_for_load", {"timeout":timeout})
46
+ async def sleep(self, seconds): return await self._request("browser.sleep", {"seconds":seconds})
47
+ async def click(self, selector): return await self._request("element.click", {"selector":selector})
48
+ async def type(self, selector, text): return await self._request("element.type", {"selector":selector,"text":text})
49
+ async def clear(self, selector): return await self._request("element.clear", {"selector":selector})
50
+ async def get_text(self, selector): return await self._request("element.get_text", {"selector":selector})
51
+ async def get_attribute(self, selector, attribute): return await self._request("element.get_attribute", {"selector":selector,"attribute":attribute})
52
+ async def get_html(self, selector): return await self._request("element.get_html", {"selector":selector})
53
+ async def find(self, selector): return await self._request("element.find", {"selector":selector})
54
+ async def find_all(self, selector): return await self._request("element.find_all", {"selector":selector})
55
+ async def exists(self, selector): return await self._request("element.exists", {"selector":selector})
56
+ async def wait_for_element(self, selector, timeout=10): return await self._request("element.wait", {"selector":selector,"timeout":timeout})
57
+ async def press(self, key): return await self._request("keyboard.press", {"key":key})
58
+ async def hotkey(self, *keys): return await self._request("keyboard.hotkey", {"keys":list(keys)})
59
+ async def scroll(self, x=0, y=0): return await self._request("mouse.scroll", {"x":x,"y":y})
60
+ async def move(self, x, y): return await self._request("mouse.move", {"x":x,"y":y})
61
+ async def new_tab(self, url=None): return await self._request("tabs.new", {"url":url})
62
+ async def close_tab(self, tab_id): return await self._request("tabs.close", {"tab_id":tab_id})
63
+ async def switch_tab(self, tab_id): return await self._request("tabs.switch", {"tab_id":tab_id})
64
+ async def get_tabs(self): return await self._request("tabs.list")
65
+ async def active_tab(self): return await self._request("tabs.active")
66
+
67
+ async def create_async_browser(api_key, host="127.0.0.1", port=8765, timeout=15):
68
+ from .bridge import ensure_async_bridge
69
+ await ensure_async_bridge(api_key, host, port)
70
+ connection = await AsyncConnection(api_key, host, port, timeout).connect()
71
+ return AsyncBrowser(connection)
@@ -0,0 +1,45 @@
1
+ """Configuration helpers. Secrets are stored with restrictive permissions where supported."""
2
+ from __future__ import annotations
3
+ import json, os, secrets
4
+ from pathlib import Path
5
+ from .exceptions import ChronimError
6
+
7
+ DEFAULT_HOST = "127.0.0.1"
8
+ DEFAULT_PORT = 8765
9
+ DEFAULT_TIMEOUT = 15.0
10
+
11
+ def config_path() -> Path:
12
+ base = Path(os.environ.get("APPDATA") or (Path.home() / ".config"))
13
+ return base / "chronim" / "config.json"
14
+
15
+ def get_api_key() -> str:
16
+ """Return CHRONIM_API_KEY or create/read a per-user local key."""
17
+ env = os.environ.get("CHRONIM_API_KEY")
18
+ if env:
19
+ if len(env) < 32:
20
+ raise ChronimError("CHRONIM_API_KEY must contain at least 32 characters")
21
+ return env
22
+ path = config_path()
23
+ try:
24
+ path.parent.mkdir(parents=True, exist_ok=True)
25
+ if path.exists():
26
+ data = json.loads(path.read_text(encoding="utf-8"))
27
+ key = data.get("api_key")
28
+ if isinstance(key, str) and len(key) >= 32:
29
+ return key
30
+ raise ChronimError(f"Invalid Chronim key configuration: {path}")
31
+ key = secrets.token_urlsafe(32)
32
+ path.write_text(json.dumps({"api_key": key}, indent=2), encoding="utf-8")
33
+ try:
34
+ path.chmod(0o600)
35
+ except OSError:
36
+ pass
37
+ return key
38
+ except ChronimError:
39
+ raise
40
+ except (OSError, ValueError) as exc:
41
+ raise ChronimError(f"Could not read or create Chronim configuration at {path}: {exc}") from exc
42
+
43
+ def generate_api_key() -> str:
44
+ """Generate a cryptographically secure key suitable for CHRONIM_API_KEY."""
45
+ return secrets.token_urlsafe(32)
@@ -0,0 +1,80 @@
1
+ """Authenticated request/response WebSocket clients (sync and async)."""
2
+ from __future__ import annotations
3
+ import asyncio, threading, uuid
4
+ from typing import Any
5
+ import websockets
6
+ from .exceptions import AuthenticationError, ConnectionError, ProtocolError, TimeoutError
7
+ from .protocol import dumps, loads, request
8
+
9
+ class AsyncConnection:
10
+ def __init__(self, api_key: str, host: str = "127.0.0.1", port: int = 8765, timeout: float = 15):
11
+ self.api_key, self.uri, self.timeout = api_key, f"ws://{host}:{port}", timeout
12
+ self.ws = None; self._pending: dict[str, asyncio.Future] = {}; self._reader = None; self._send_lock = asyncio.Lock()
13
+ async def connect(self):
14
+ try:
15
+ self.ws = await websockets.connect(self.uri, max_size=16*1024*1024, open_timeout=self.timeout)
16
+ await self.ws.send(dumps({"type":"hello","role":"client","token":self.api_key}))
17
+ auth = loads(await asyncio.wait_for(self.ws.recv(), self.timeout))
18
+ if not auth.get("success"):
19
+ raise AuthenticationError((auth.get("error") or {}).get("message", "Chronim authentication failed"))
20
+ self._reader = asyncio.create_task(self._read_loop())
21
+ return self
22
+ except AuthenticationError: raise
23
+ except Exception as exc: raise ConnectionError(f"Could not connect to Chronim bridge at {self.uri}: {exc}") from exc
24
+ async def _read_loop(self):
25
+ try:
26
+ async for raw in self.ws:
27
+ msg = loads(raw); rid = msg.get("id"); future = self._pending.get(rid)
28
+ if future and not future.done(): future.set_result(msg)
29
+ except Exception as exc:
30
+ for f in self._pending.values():
31
+ if not f.done(): f.set_exception(ConnectionError(f"Chronim bridge disconnected: {exc}"))
32
+ else:
33
+ for f in self._pending.values():
34
+ if not f.done(): f.set_exception(ConnectionError("Chronim bridge closed the connection"))
35
+ async def request(self, action: str, payload: dict[str, Any] | None = None):
36
+ if not self.ws: raise ConnectionError("Not connected to Chronim bridge")
37
+ msg = request(action, payload); rid = msg["id"]; future = asyncio.get_running_loop().create_future(); self._pending[rid] = future
38
+ try:
39
+ async with self._send_lock: await self.ws.send(dumps(msg))
40
+ try: response = await asyncio.wait_for(future, self.timeout)
41
+ except asyncio.TimeoutError as exc: raise TimeoutError(f"Chronim request {action} timed out after {self.timeout:g}s") from exc
42
+ if not response.get("success"):
43
+ error = response.get("error") or {}; code, text = error.get("code"), error.get("message", "Chrome command failed")
44
+ if code == "ELEMENT_NOT_FOUND":
45
+ from .exceptions import ElementNotFoundError
46
+ raise ElementNotFoundError(text)
47
+ if code == "TIMEOUT": raise TimeoutError(text)
48
+ if code == "EXTENSION_NOT_FOUND":
49
+ from .exceptions import ExtensionNotFoundError
50
+ raise ExtensionNotFoundError(text)
51
+ if code == "PROTOCOL_ERROR": raise ProtocolError(text)
52
+ if code == "CONNECTION_ERROR": raise ConnectionError(text)
53
+ from .exceptions import BrowserError
54
+ raise BrowserError(text)
55
+ return response.get("result")
56
+ finally: self._pending.pop(rid, None)
57
+ async def close(self):
58
+ if self.ws:
59
+ await self.ws.close(); self.ws = None
60
+ if self._reader:
61
+ self._reader.cancel(); self._reader = None
62
+
63
+ class SyncConnection:
64
+ def __init__(self, api_key: str, host: str = "127.0.0.1", port: int = 8765, timeout: float = 15):
65
+ self.loop = asyncio.new_event_loop(); self.ready = threading.Event(); self.error = None
66
+ self.thread = threading.Thread(target=self._run, daemon=True, name="chronim-client"); self.thread.start()
67
+ self.conn = AsyncConnection(api_key, host, port, timeout)
68
+ fut = asyncio.run_coroutine_threadsafe(self.conn.connect(), self.loop)
69
+ try: fut.result(timeout + 3)
70
+ except Exception as exc:
71
+ self.loop.call_soon_threadsafe(self.loop.stop)
72
+ raise exc
73
+ def _run(self):
74
+ asyncio.set_event_loop(self.loop); self.loop.run_forever()
75
+ def request(self, action, payload=None):
76
+ return asyncio.run_coroutine_threadsafe(self.conn.request(action, payload), self.loop).result(self.conn.timeout + 2)
77
+ def close(self):
78
+ if self.conn.ws:
79
+ asyncio.run_coroutine_threadsafe(self.conn.close(), self.loop).result(3)
80
+ self.loop.call_soon_threadsafe(self.loop.stop)
@@ -0,0 +1,12 @@
1
+ """Element operations exposed on Browser."""
2
+ class Elements:
3
+ def click(self, selector): return self._request("element.click", {"selector": selector})
4
+ def type(self, selector, text): return self._request("element.type", {"selector": selector, "text": text})
5
+ def clear(self, selector): return self._request("element.clear", {"selector": selector})
6
+ def get_text(self, selector): return self._request("element.get_text", {"selector": selector})
7
+ def get_attribute(self, selector, attribute): return self._request("element.get_attribute", {"selector": selector, "attribute": attribute})
8
+ def get_html(self, selector): return self._request("element.get_html", {"selector": selector})
9
+ def find(self, selector): return self._request("element.find", {"selector": selector})
10
+ def find_all(self, selector): return self._request("element.find_all", {"selector": selector})
11
+ def exists(self, selector): return self._request("element.exists", {"selector": selector})
12
+ def wait_for_element(self, selector, timeout=10): return self._request("element.wait", {"selector": selector, "timeout": timeout})
@@ -0,0 +1,32 @@
1
+ """Public exception hierarchy for Chronim."""
2
+
3
+ class ChronimError(Exception):
4
+ """Base class for errors raised by Chronim."""
5
+
6
+ class ConnectionError(ChronimError):
7
+ """The local bridge could not be reached or disconnected."""
8
+ code = "CONNECTION_ERROR"
9
+
10
+ class AuthenticationError(ConnectionError):
11
+ """The bridge rejected the configured API key."""
12
+ code = "AUTHENTICATION_FAILED"
13
+
14
+ class ElementNotFoundError(ChronimError):
15
+ """A selector did not match an element."""
16
+ code = "ELEMENT_NOT_FOUND"
17
+
18
+ class TimeoutError(ChronimError):
19
+ """An operation did not complete before its timeout."""
20
+ code = "TIMEOUT"
21
+
22
+ class BrowserError(ChronimError):
23
+ """Chrome could not perform the requested operation."""
24
+ code = "BROWSER_ERROR"
25
+
26
+ class ProtocolError(ChronimError):
27
+ """A peer sent an invalid or unsupported protocol message."""
28
+ code = "PROTOCOL_ERROR"
29
+
30
+ class ExtensionNotFoundError(ConnectionError):
31
+ """No authenticated Chronim extension is connected."""
32
+ code = "EXTENSION_NOT_FOUND"
@@ -0,0 +1,4 @@
1
+ """Keyboard operations exposed on Browser."""
2
+ class Keyboard:
3
+ def press(self, key): return self._request("keyboard.press", {"key": key})
4
+ def hotkey(self, *keys): return self._request("keyboard.hotkey", {"keys": list(keys)})
@@ -0,0 +1,4 @@
1
+ """Mouse operations exposed on Browser."""
2
+ class Mouse:
3
+ def scroll(self, x=0, y=0): return self._request("mouse.scroll", {"x": x, "y": y})
4
+ def move(self, x, y): return self._request("mouse.move", {"x": x, "y": y})
@@ -0,0 +1,40 @@
1
+ """JSON protocol validation and message constructors."""
2
+ from __future__ import annotations
3
+ import json, uuid
4
+ from typing import Any
5
+ from .exceptions import ProtocolError
6
+
7
+ MAX_MESSAGE_BYTES = 16 * 1024 * 1024
8
+
9
+ def request(action: str, payload: dict[str, Any] | None = None, request_id: str | None = None) -> dict[str, Any]:
10
+ if not isinstance(action, str) or not action:
11
+ raise ProtocolError("Action must be a non-empty string")
12
+ return {"type": "request", "id": request_id or uuid.uuid4().hex, "action": action, "payload": payload or {}}
13
+
14
+ def dumps(message: dict[str, Any]) -> str:
15
+ try:
16
+ result = json.dumps(message, separators=(",", ":"), ensure_ascii=False)
17
+ except (TypeError, ValueError) as exc:
18
+ raise ProtocolError(f"Message cannot be encoded as JSON: {exc}") from exc
19
+ if len(result.encode("utf-8")) > MAX_MESSAGE_BYTES:
20
+ raise ProtocolError("Message exceeds the 16 MiB protocol limit")
21
+ return result
22
+
23
+ def loads(raw: str | bytes) -> dict[str, Any]:
24
+ if isinstance(raw, bytes):
25
+ if len(raw) > MAX_MESSAGE_BYTES:
26
+ raise ProtocolError("Message exceeds the 16 MiB protocol limit")
27
+ raw = raw.decode("utf-8")
28
+ if not isinstance(raw, str) or len(raw.encode("utf-8")) > MAX_MESSAGE_BYTES:
29
+ raise ProtocolError("Invalid or oversized message")
30
+ try:
31
+ value = json.loads(raw)
32
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
33
+ raise ProtocolError("Message is not valid JSON") from exc
34
+ if not isinstance(value, dict):
35
+ raise ProtocolError("Protocol message must be a JSON object")
36
+ return value
37
+
38
+ def validate_request(message: dict[str, Any]) -> None:
39
+ if message.get("type") != "request" or not isinstance(message.get("id"), str) or not isinstance(message.get("action"), str) or not isinstance(message.get("payload", {}), dict):
40
+ raise ProtocolError("Expected a request with string id/action and object payload")
@@ -0,0 +1,3 @@
1
+ """Screenshot helper."""
2
+ class Screenshot:
3
+ def screenshot(self): return self._request("browser.screenshot", {})
@@ -0,0 +1,7 @@
1
+ """Tab operations exposed on Browser."""
2
+ class Tabs:
3
+ def new_tab(self, url=None): return self._request("tabs.new", {"url": url})
4
+ def close_tab(self, tab_id): return self._request("tabs.close", {"tab_id": tab_id})
5
+ def switch_tab(self, tab_id): return self._request("tabs.switch", {"tab_id": tab_id})
6
+ def get_tabs(self): return self._request("tabs.list", {})
7
+ def active_tab(self): return self._request("tabs.active", {})
@@ -0,0 +1,182 @@
1
+ Metadata-Version: 2.4
2
+ Name: chronim
3
+ Version: 0.1.0
4
+ Summary: Control Google Chrome directly from Python through a local extension bridge.
5
+ Author: Dima
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: websockets<16,>=12
14
+ Dynamic: license-file
15
+
16
+ # Chronim
17
+
18
+ **Control your browser. Directly from Python.** Chronim connects Python to Chrome through a Manifest V3 extension and an authenticated WebSocket server bound to localhost. It does not use Selenium, Playwright, or Puppeteer.
19
+
20
+ > The source project is implemented here. Actual browser operations require installing the extension and having Chrome connected. This environment does not have a confirmed live Chrome session, so the examples below are not represented as end-to-end browser tested.
21
+
22
+ ## What it does
23
+
24
+ - Open, navigate, inspect, and close Chrome tabs.
25
+ - Click and inspect DOM elements by CSS selector, type into fields, and wait for elements.
26
+ - Send DOM keyboard and pointer events, take a visible-tab screenshot, and run JavaScript in the active page's main world.
27
+ - Use a synchronous API or an `asyncio` API over the same JSON request/response protocol.
28
+ - Authenticate Python and the extension with a random per-user key; bind the bridge to `127.0.0.1` by default.
29
+
30
+ The main flow is:
31
+
32
+ ```text
33
+ Python Browser API ──WebSocket──> Local Bridge ──WebSocket──> MV3 extension ──Chrome APIs/DOM──> Chrome
34
+ ```
35
+
36
+ The bridge multiplexes responses by request ID, validates JSON messages, restricts incoming peers to loopback, checks browser extension origins, and sends only supported action names to the extension. It does not expose OS command execution or filesystem access. Page actions are limited by Chrome's extension and page security restrictions. DOM keyboard/mouse methods dispatch browser events; they do not emulate physical hardware input.
37
+
38
+ ## Install
39
+
40
+ From this directory, install the package and dependency:
41
+
42
+ ```bash
43
+ python -m pip install .
44
+ ```
45
+
46
+ Python 3.10+ is required. The first `chronim.connect()` creates a random key in the current user's config directory (`%APPDATA%/chronim/config.json` on Windows, `~/.config/chronim/config.json` elsewhere) and starts the local bridge on `127.0.0.1:8765`. The config file is created with owner-only permissions where supported. Alternatively, set `CHRONIM_API_KEY` to a key of at least 32 characters; `chronim.generate_api_key()` creates a suitable key.
47
+
48
+ ## Install the Chrome extension
49
+
50
+ 1. Open `chrome://extensions` in Chrome and enable **Developer mode**.
51
+ 2. Choose **Load unpacked** and select this project's `extension/` folder.
52
+ 3. Start a Python script that calls `chronim.connect()` (this starts the bridge).
53
+ 4. Click the Chronim toolbar icon. In Python, print your key with:
54
+
55
+ ```bash
56
+ python -c "import chronim; print(chronim.get_api_key())"
57
+ ```
58
+
59
+ 5. Paste that key into the extension popup and choose **Save key and connect**. The popup should show **Connected**.
60
+
61
+ The key is stored in Chrome extension local storage and the per-user Chronim config. Do not share either. To change keys, set `CHRONIM_API_KEY` in the Python process and update the popup to the same value. The extension reconnects automatically when the local bridge becomes available. Use the popup's Save action after starting the Python process if the extension was loaded before the bridge.
62
+
63
+ The extension requests `tabs`, `activeTab`, `scripting`, and `storage`; host access to HTTP(S) pages is used to perform DOM actions across tabs. Chrome internal pages, the Chrome Web Store, and pages that block extension scripting cannot be automated.
64
+
65
+ ## First program
66
+
67
+ ```python
68
+ import chronim
69
+
70
+ browser = chronim.connect()
71
+ try:
72
+ browser.open("https://example.com")
73
+ browser.wait_for_load()
74
+ print(browser.title())
75
+ print(browser.url())
76
+ finally:
77
+ browser.disconnect()
78
+ ```
79
+
80
+ Use `browser.close()` to close the active Chrome tab and disconnect the Python client. Use `disconnect()` when you only want to close the Python connection.
81
+
82
+ ## Examples
83
+
84
+ See [`examples/basic.py`](examples/basic.py), [`examples/google_search.py`](examples/google_search.py), [`examples/tabs.py`](examples/tabs.py), and [`examples/async_example.py`](examples/async_example.py).
85
+
86
+ ```python
87
+ import chronim
88
+
89
+ browser = chronim.connect()
90
+ browser.open("https://www.google.com")
91
+ browser.wait_for_load()
92
+ browser.type("textarea[name=q]", "Chronim")
93
+ browser.press("ENTER")
94
+ browser.wait_for_load()
95
+ print(browser.title())
96
+ browser.disconnect()
97
+ ```
98
+
99
+ Async version:
100
+
101
+ ```python
102
+ import asyncio
103
+ import chronim
104
+
105
+ async def main():
106
+ browser = await chronim.connect_async()
107
+ try:
108
+ await browser.open("https://example.com")
109
+ await browser.wait_for_load()
110
+ print(await browser.title())
111
+ finally:
112
+ await browser.disconnect()
113
+
114
+ asyncio.run(main())
115
+ ```
116
+
117
+ ## API reference
118
+
119
+ `chronim.connect(*, api_key=None, host="127.0.0.1", port=8765, timeout=15)` returns a synchronous `Browser`. `await chronim.connect_async(...)` returns an `AsyncBrowser`. The async API exposes the same browser, element, keyboard, mouse, and tab methods with `await`.
120
+
121
+ | Methods | Arguments / result |
122
+ |---|---|
123
+ | `open(url)`, `back()`, `forward()`, `refresh()`, `close()`, `disconnect()` | Navigate or close a tab/client; navigation calls return operation results. `close()` closes active tab and disconnects; `disconnect()` only disconnects the client. |
124
+ | `title()`, `url()` | Return active tab title and URL strings. |
125
+ | `screenshot()` | Return Chrome's PNG data URL for the visible tab. |
126
+ | `execute_js(code)` | Evaluate JavaScript in the active page's main world and return its serializable result. It has no Node.js or OS APIs. Chrome applies that page's Content Security Policy, so pages that disallow dynamic evaluation may reject the operation. |
127
+ | `wait_for_load(timeout=30)`, `sleep(seconds)` | Wait for active tab load completion or for a bounded delay. |
128
+ | `click(selector)`, `type(selector, text)`, `clear(selector)` | Click or edit the first matching CSS element. `type` replaces the input value and dispatches input/change events. |
129
+ | `get_text(selector)`, `get_attribute(selector, attribute)`, `get_html(selector)` | Return text, an attribute (or `None`), or inner HTML. |
130
+ | `find(selector)`, `find_all(selector)`, `exists(selector)` | Return element description(s), or a boolean. Descriptions include tag, id, classes, short text, and attributes. |
131
+ | `wait_for_element(selector, timeout=10)` | Poll for an element and return its description. |
132
+ | `press(key)`, `hotkey(*keys)` | Dispatch DOM keyboard events, e.g. `press("ENTER")` or `hotkey("CTRL", "A")`. |
133
+ | `scroll(x=0, y=0)`, `move(x, y)` | Scroll by pixel offsets or dispatch a pointer move at viewport coordinates. |
134
+ | `new_tab(url=None)`, `close_tab(tab_id)`, `switch_tab(tab_id)` | Create, close, or activate a tab. Creation and switching return tab information. |
135
+ | `get_tabs()`, `active_tab()` | Return tab metadata dictionaries. |
136
+
137
+ `get_api_key()` reads/creates the local key. `generate_api_key()` returns a secure random key for use as `CHRONIM_API_KEY`.
138
+
139
+ ## Errors
140
+
141
+ All library errors inherit from `ChronimError`:
142
+
143
+ - `ConnectionError`: the local bridge is unavailable or disconnected.
144
+ - `AuthenticationError`: the key was rejected.
145
+ - `ExtensionNotFoundError`: the extension is not connected to the bridge.
146
+ - `ElementNotFoundError`: a selector has no matching element.
147
+ - `TimeoutError`: a command or wait expired.
148
+ - `BrowserError`: Chrome or the page rejected an operation.
149
+ - `ProtocolError`: the message was malformed or unsupported.
150
+
151
+ ```python
152
+ import chronim
153
+
154
+ try:
155
+ browser = chronim.connect()
156
+ print(browser.get_text("h1"))
157
+ except chronim.ExtensionNotFoundError as exc:
158
+ print(f"Open the Chronim extension popup and connect it: {exc}")
159
+ finally:
160
+ if "browser" in locals():
161
+ browser.disconnect()
162
+ ```
163
+
164
+ ## Troubleshooting
165
+
166
+ - **Popup says disconnected:** start the Python process first, check that it listens on port 8765, then save/connect the key again.
167
+ - **Authentication failed:** compare the extension key with `chronim.get_api_key()` in the same environment as the script. An environment key overrides the local config.
168
+ - **Address already in use:** another Chronim process may own port 8765. Stop that process or choose a custom port consistently for Python and the popup.
169
+ - **Element not found:** wait for page load, verify the CSS selector in DevTools, and make sure the target is not inside a cross-origin iframe.
170
+ - **Chrome page cannot be scripted:** Chrome internal pages, store pages, and certain restricted frames disallow content scripts.
171
+ - **Screenshot unavailable:** Chrome may reject capture for a restricted or protected tab.
172
+ - **No physical keyboard/mouse behavior:** Chronim emits DOM events. Sites may ignore synthetic events where trusted user input is required.
173
+
174
+ ## Development checks
175
+
176
+ Run the included standard-library tests with:
177
+
178
+ ```bash
179
+ python -m unittest discover -s tests -v
180
+ ```
181
+
182
+ Those tests cover the protocol and Python API surface without requiring a live Chrome session. A real-browser smoke test still requires installing the extension and connecting Chrome as described above.
@@ -0,0 +1,22 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ chronim/__init__.py
5
+ chronim/bridge.py
6
+ chronim/browser.py
7
+ chronim/config.py
8
+ chronim/connection.py
9
+ chronim/elements.py
10
+ chronim/exceptions.py
11
+ chronim/keyboard.py
12
+ chronim/mouse.py
13
+ chronim/protocol.py
14
+ chronim/screenshot.py
15
+ chronim/tabs.py
16
+ chronim.egg-info/PKG-INFO
17
+ chronim.egg-info/SOURCES.txt
18
+ chronim.egg-info/dependency_links.txt
19
+ chronim.egg-info/requires.txt
20
+ chronim.egg-info/top_level.txt
21
+ tests/test_api.py
22
+ tests/test_protocol.py
@@ -0,0 +1 @@
1
+ websockets<16,>=12
@@ -0,0 +1 @@
1
+ chronim
@@ -0,0 +1,20 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "chronim"
7
+ version = "0.1.0"
8
+ description = "Control Google Chrome directly from Python through a local extension bridge."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Dima" }]
13
+ dependencies = ["websockets>=12,<16"]
14
+ classifiers = ["Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Operating System :: OS Independent"]
15
+
16
+ [tool.setuptools.packages.find]
17
+ include = ["chronim*"]
18
+
19
+ [tool.pytest.ini_options]
20
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,30 @@
1
+ import asyncio
2
+ import unittest
3
+ import chronim
4
+ from chronim.browser import Browser, AsyncBrowser
5
+
6
+ class FakeSyncConnection:
7
+ def __init__(self): self.calls=[]; self.closed=False
8
+ def request(self, action, payload=None): self.calls.append((action,payload)); return "ok"
9
+ def close(self): self.closed=True
10
+
11
+ class FakeAsyncConnection:
12
+ def __init__(self): self.calls=[]; self.closed=False
13
+ async def request(self, action, payload=None): self.calls.append((action,payload)); return "ok"
14
+ async def close(self): self.closed=True
15
+
16
+ class ApiTests(unittest.TestCase):
17
+ def test_public_api_and_sync_dispatch(self):
18
+ connection=FakeSyncConnection(); browser=Browser(connection)
19
+ self.assertEqual(browser.open("https://example.com"), "ok")
20
+ self.assertEqual(connection.calls[-1], ("browser.open", {"url":"https://example.com"}))
21
+ self.assertTrue(hasattr(chronim,"connect_async"))
22
+
23
+ def test_async_dispatch(self):
24
+ async def run():
25
+ connection=FakeAsyncConnection(); browser=AsyncBrowser(connection)
26
+ self.assertEqual(await browser.click("#go"), "ok")
27
+ self.assertEqual(connection.calls[-1], ("element.click", {"selector":"#go"}))
28
+ asyncio.run(run())
29
+
30
+ if __name__ == "__main__": unittest.main()
@@ -0,0 +1,20 @@
1
+ import unittest
2
+ from chronim.protocol import dumps, loads, request, validate_request
3
+ from chronim.exceptions import ProtocolError
4
+
5
+ class ProtocolTests(unittest.TestCase):
6
+ def test_request_round_trip(self):
7
+ original = request("browser.open", {"url": "https://example.com"}, "req-1")
8
+ decoded = loads(dumps(original))
9
+ validate_request(decoded)
10
+ self.assertEqual(decoded, original)
11
+
12
+ def test_rejects_non_object(self):
13
+ with self.assertRaises(ProtocolError):
14
+ loads("[]")
15
+
16
+ def test_rejects_invalid_request(self):
17
+ with self.assertRaises(ProtocolError):
18
+ validate_request({"id": 3, "action": "browser.open"})
19
+
20
+ if __name__ == "__main__": unittest.main()