tabwright 0.1.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.
- tabwright/__init__.py +3 -0
- tabwright/adapters/__init__.py +20 -0
- tabwright/adapters/chromium.py +133 -0
- tabwright/adapters/firefox.py +319 -0
- tabwright/adapters/snss.py +261 -0
- tabwright/cli.py +461 -0
- tabwright/extension/background.js +161 -0
- tabwright/extension/manifest.json +25 -0
- tabwright/gui.py +672 -0
- tabwright/library.py +52 -0
- tabwright/live.py +126 -0
- tabwright/mcp_server.py +107 -0
- tabwright/model.py +183 -0
- tabwright/native_host.py +143 -0
- tabwright/policy.py +36 -0
- tabwright/tools.py +316 -0
- tabwright-0.1.0.dist-info/METADATA +275 -0
- tabwright-0.1.0.dist-info/RECORD +21 -0
- tabwright-0.1.0.dist-info/WHEEL +4 -0
- tabwright-0.1.0.dist-info/entry_points.txt +2 -0
- tabwright-0.1.0.dist-info/licenses/LICENSE +21 -0
tabwright/library.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Named sets: saved session/window/group/tabset documents in the XDG data dir."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from tabwright import model
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def library_dir() -> Path:
|
|
12
|
+
base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share"))
|
|
13
|
+
d = base / "tabwright" / "library"
|
|
14
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
15
|
+
return d
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def save(name: str, node: model.Node) -> Path:
|
|
19
|
+
path = library_dir() / f"{name}.json"
|
|
20
|
+
path.write_text(model.dumps(node))
|
|
21
|
+
return path
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def load(name: str) -> model.Node:
|
|
25
|
+
path = library_dir() / f"{name}.json"
|
|
26
|
+
if not path.exists():
|
|
27
|
+
raise SystemExit(f"no saved set named {name!r} in {library_dir()}")
|
|
28
|
+
return model.loads(path.read_text())
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def names() -> list[tuple[str, str]]:
|
|
32
|
+
out = []
|
|
33
|
+
for p in sorted(library_dir().glob("*.json")):
|
|
34
|
+
out.append((p.stem, model.loads(p.read_text()).__class__.__name__.lower()))
|
|
35
|
+
return out
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def rename(old: str, new: str) -> Path:
|
|
39
|
+
src = library_dir() / f"{old}.json"
|
|
40
|
+
dst = library_dir() / f"{new}.json"
|
|
41
|
+
if not src.exists():
|
|
42
|
+
raise SystemExit(f"no saved set named {old!r}")
|
|
43
|
+
if dst.exists():
|
|
44
|
+
raise SystemExit(f"{new!r} already exists")
|
|
45
|
+
return src.rename(dst)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def delete(name: str) -> None:
|
|
49
|
+
path = library_dir() / f"{name}.json"
|
|
50
|
+
if not path.exists():
|
|
51
|
+
raise SystemExit(f"no saved set named {name!r}")
|
|
52
|
+
path.unlink()
|
tabwright/live.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Live path: talk to the companion extension through the native messaging host.
|
|
2
|
+
|
|
3
|
+
The browser launches ``tabwright.native_host`` when the extension connects; the host
|
|
4
|
+
listens on a Unix socket and relays one JSON request per connection to the extension.
|
|
5
|
+
This module is the client side plus the installer for the host manifest.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import socket
|
|
14
|
+
import stat
|
|
15
|
+
import sys
|
|
16
|
+
from importlib import resources
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from tabwright import adapters, model
|
|
20
|
+
from tabwright.adapters import chromium, firefox
|
|
21
|
+
|
|
22
|
+
HOST_NAME = "com.mostlyharmless.tabwright"
|
|
23
|
+
GECKO_ID = "tabwright@mostlyharmless.ai"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def extension_dir() -> Path:
|
|
27
|
+
return Path(str(resources.files("tabwright") / "extension"))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def extension_id() -> str:
|
|
31
|
+
"""Chromium derives an unpacked extension's id from the manifest ``key`` (SPKI DER, sha256, a-p)."""
|
|
32
|
+
import base64
|
|
33
|
+
|
|
34
|
+
key = json.loads((extension_dir() / "manifest.json").read_text())["key"]
|
|
35
|
+
digest = hashlib.sha256(base64.b64decode(key)).hexdigest()[:32]
|
|
36
|
+
return "".join(chr(ord("a") + int(c, 16)) for c in digest)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def key(browser: str, data_dir: Path | None) -> str:
|
|
40
|
+
"""One host, socket and wrapper per browser user-data-dir."""
|
|
41
|
+
if data_dir is None:
|
|
42
|
+
return browser
|
|
43
|
+
return f"{browser}-{hashlib.sha1(str(Path(data_dir).resolve()).encode()).hexdigest()[:8]}"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def socket_path(browser: str, data_dir: Path | None = None) -> Path:
|
|
47
|
+
if p := os.environ.get("TABWRIGHT_SOCKET"):
|
|
48
|
+
return Path(p)
|
|
49
|
+
run = Path(os.environ.get("XDG_RUNTIME_DIR", f"/tmp/tabwright-{os.getuid()}"))
|
|
50
|
+
return run / "tabwright" / f"{key(browser, data_dir)}.sock"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def request(op: str, browser: str = "brave", data_dir: Path | None = None, timeout: float = 60, **params):
|
|
54
|
+
path = socket_path(browser, data_dir)
|
|
55
|
+
s = socket.socket(socket.AF_UNIX)
|
|
56
|
+
s.settimeout(timeout)
|
|
57
|
+
try:
|
|
58
|
+
s.connect(str(path))
|
|
59
|
+
except OSError as e:
|
|
60
|
+
raise SystemExit(
|
|
61
|
+
f"no live bridge at {path} ({e.strerror}); is {browser} running with the companion "
|
|
62
|
+
"extension loaded? see `tabwright live install`"
|
|
63
|
+
) from None
|
|
64
|
+
with s, s.makefile("rwb") as f:
|
|
65
|
+
f.write(json.dumps({"op": op, **params}).encode() + b"\n")
|
|
66
|
+
f.flush()
|
|
67
|
+
line = f.readline()
|
|
68
|
+
if not line:
|
|
69
|
+
raise SystemExit("live bridge closed the connection without a reply")
|
|
70
|
+
reply = json.loads(line)
|
|
71
|
+
if not reply.get("ok"):
|
|
72
|
+
raise SystemExit(f"browser refused {op}: {reply.get('error')}")
|
|
73
|
+
return reply["result"]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def snapshot(browser: str = "brave", data_dir: Path | None = None) -> model.Session:
|
|
77
|
+
s = model.from_dict(request("snapshot", browser, data_dir))
|
|
78
|
+
s.browser = browser
|
|
79
|
+
return s
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def apply(session: model.Session, browser: str = "brave", data_dir: Path | None = None) -> model.Session:
|
|
83
|
+
s = model.from_dict(request("apply", browser, data_dir, timeout=600, session=model.to_dict(session)))
|
|
84
|
+
s.browser = browser
|
|
85
|
+
return s
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def extensions(browser: str = "brave", data_dir: Path | None = None) -> list[dict]:
|
|
89
|
+
return request("extensions", browser, data_dir)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def set_extension(ext_id: str, enabled: bool, browser: str = "brave", data_dir: Path | None = None) -> dict:
|
|
93
|
+
return request("set_extension", browser, data_dir, ext=ext_id, enabled=enabled)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def install(browser: str = "brave") -> tuple[Path, Path]:
|
|
97
|
+
"""Write the host wrapper and the browser's native-messaging manifest; returns both paths.
|
|
98
|
+
|
|
99
|
+
Chromium reads manifests from the *default* user data dir even when launched with
|
|
100
|
+
``--user-data-dir``, so one manifest per browser serves every profile and data dir; the
|
|
101
|
+
host works out which data dir it belongs to from its parent process (``native_host``).
|
|
102
|
+
"""
|
|
103
|
+
adapters.get(browser)
|
|
104
|
+
share = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / "tabwright"
|
|
105
|
+
share.mkdir(parents=True, exist_ok=True)
|
|
106
|
+
wrapper = share / f"host-{browser}"
|
|
107
|
+
wrapper.write_text(f"#!/bin/sh\nexec {_q(sys.executable)} -m tabwright.native_host {browser}\n")
|
|
108
|
+
wrapper.chmod(wrapper.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
|
109
|
+
body = {"name": HOST_NAME, "description": "tabwright live bridge", "path": str(wrapper), "type": "stdio"}
|
|
110
|
+
if browser in firefox.BROWSERS:
|
|
111
|
+
# Firefox (deb, snap via the WebExtensions portal, Tor Browser) reads the user-level dir
|
|
112
|
+
hosts = Path.home() / ".mozilla/native-messaging-hosts"
|
|
113
|
+
body["allowed_extensions"] = [GECKO_ID]
|
|
114
|
+
else:
|
|
115
|
+
hosts = chromium.user_data_dir(browser) / "NativeMessagingHosts"
|
|
116
|
+
body["allowed_origins"] = [f"chrome-extension://{extension_id()}/"]
|
|
117
|
+
hosts.mkdir(parents=True, exist_ok=True)
|
|
118
|
+
manifest = hosts / f"{HOST_NAME}.json"
|
|
119
|
+
manifest.write_text(json.dumps(body, indent=2) + "\n")
|
|
120
|
+
return wrapper, manifest
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _q(s: str) -> str:
|
|
124
|
+
import shlex
|
|
125
|
+
|
|
126
|
+
return shlex.quote(s)
|
tabwright/mcp_server.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""MCP server: the CLI contract over the Model Context Protocol (stdio).
|
|
2
|
+
|
|
3
|
+
``run`` is the whole CLI (same arguments, same stdout/stderr split, same exit codes);
|
|
4
|
+
``snapshot`` and ``push`` are typed shortcuts for the two calls an agent makes most.
|
|
5
|
+
The model schema is served as a resource. Needs the ``agent`` extra.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import io
|
|
12
|
+
import json
|
|
13
|
+
import tempfile
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, TypedDict
|
|
16
|
+
|
|
17
|
+
from mcp.server import MCPServer
|
|
18
|
+
|
|
19
|
+
from tabwright import cli, model
|
|
20
|
+
|
|
21
|
+
server = MCPServer(
|
|
22
|
+
"tabwright", instructions="Browser session manager; call `run` with tabwright CLI arguments."
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SessionDoc(TypedDict):
|
|
27
|
+
"""A session in the model shape; see the tabwright://schema resource."""
|
|
28
|
+
|
|
29
|
+
kind: str
|
|
30
|
+
browser: str
|
|
31
|
+
windows: list[dict[str, Any]]
|
|
32
|
+
extra: dict[str, Any]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Result(TypedDict):
|
|
36
|
+
code: int
|
|
37
|
+
stdout: str
|
|
38
|
+
stderr: str
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _cli(argv: list[str]) -> Result:
|
|
42
|
+
out, err = io.StringIO(), io.StringIO()
|
|
43
|
+
code = 0
|
|
44
|
+
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
|
45
|
+
try:
|
|
46
|
+
cli.main(argv)
|
|
47
|
+
except SystemExit as e: # argparse (2) and refusals (1 with a message)
|
|
48
|
+
if isinstance(e.code, int):
|
|
49
|
+
code = e.code
|
|
50
|
+
else:
|
|
51
|
+
code = 1
|
|
52
|
+
err.write(f"{e.code}\n")
|
|
53
|
+
return {"code": code, "stdout": out.getvalue(), "stderr": err.getvalue()}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@server.tool()
|
|
57
|
+
def run(args: list[str]) -> Result:
|
|
58
|
+
"""Run tabwright with CLI arguments, e.g. ["list", "--live", "--json"]. Returns code, stdout, stderr."""
|
|
59
|
+
return _cli(args)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@server.tool()
|
|
63
|
+
def snapshot(
|
|
64
|
+
browser: str = "brave", profile: str = "Default", live: bool = False, data_dir: str = ""
|
|
65
|
+
) -> SessionDoc:
|
|
66
|
+
"""Current session as model JSON: from the session file, or from the running browser with live=True."""
|
|
67
|
+
argv = ["list", "-b", browser, "-p", profile, "--json", *(["--live"] if live else [])]
|
|
68
|
+
if data_dir:
|
|
69
|
+
argv += ["--data-dir", data_dir]
|
|
70
|
+
r = _cli(argv)
|
|
71
|
+
if r["code"]:
|
|
72
|
+
raise RuntimeError(r["stderr"].strip())
|
|
73
|
+
return json.loads(r["stdout"])
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@server.tool()
|
|
77
|
+
def push(
|
|
78
|
+
session: dict,
|
|
79
|
+
browser: str = "brave",
|
|
80
|
+
profile: str = "Default",
|
|
81
|
+
live: bool = False,
|
|
82
|
+
data_dir: str = "",
|
|
83
|
+
dry_run: bool = False,
|
|
84
|
+
) -> Result:
|
|
85
|
+
"""Write a model-JSON session: into the running browser (live=True) or the stopped browser's profile."""
|
|
86
|
+
model.from_dict(session) # validate shape before touching anything
|
|
87
|
+
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f:
|
|
88
|
+
f.write(json.dumps(session))
|
|
89
|
+
try:
|
|
90
|
+
argv = ["push", "-f", f.name, "-b", browser, "-p", profile, "--live" if live else "--apply"]
|
|
91
|
+
if data_dir:
|
|
92
|
+
argv += ["--data-dir", data_dir]
|
|
93
|
+
if dry_run:
|
|
94
|
+
argv.append("--dry-run")
|
|
95
|
+
return _cli(argv)
|
|
96
|
+
finally:
|
|
97
|
+
Path(f.name).unlink(missing_ok=True)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@server.resource("tabwright://schema", mime_type="application/json")
|
|
101
|
+
def schema() -> str:
|
|
102
|
+
"""Model JSON Schema and command contract (same as `tabwright schema`)."""
|
|
103
|
+
return _cli(["schema"])["stdout"]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def main() -> None:
|
|
107
|
+
server.run()
|
tabwright/model.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Browser-neutral session model.
|
|
2
|
+
|
|
3
|
+
Session > Window > (Tab | Group > Tab). A window's ``items`` is the ordered tab
|
|
4
|
+
strip; a Group holds its contiguous tabs. ``extra`` on every node carries
|
|
5
|
+
browser-specific facts that adapters round-trip and the model ignores.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from dataclasses import asdict, dataclass, field
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
GROUP_COLORS = ["grey", "blue", "red", "yellow", "green", "pink", "purple", "cyan", "orange"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class Tab:
|
|
19
|
+
url: str
|
|
20
|
+
title: str = ""
|
|
21
|
+
pinned: bool = False
|
|
22
|
+
active: bool = False
|
|
23
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class Group:
|
|
28
|
+
title: str = ""
|
|
29
|
+
color: str = "grey"
|
|
30
|
+
collapsed: bool = False
|
|
31
|
+
tabs: list[Tab] = field(default_factory=list)
|
|
32
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
WINDOW_STATES = ["normal", "maximized", "minimized", "fullscreen"]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class Window:
|
|
40
|
+
items: list[Tab | Group] = field(default_factory=list)
|
|
41
|
+
# {"x", "y", "width", "height", "state"}: virtual-desktop pixels; None means "browser default".
|
|
42
|
+
# Wayland compositors ignore x/y; size and state still apply.
|
|
43
|
+
geometry: dict[str, Any] | None = None
|
|
44
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
45
|
+
|
|
46
|
+
def tabs(self) -> list[Tab]:
|
|
47
|
+
out: list[Tab] = []
|
|
48
|
+
for it in self.items:
|
|
49
|
+
out.extend(it.tabs if isinstance(it, Group) else [it])
|
|
50
|
+
return out
|
|
51
|
+
|
|
52
|
+
def groups(self) -> list[Group]:
|
|
53
|
+
return [it for it in self.items if isinstance(it, Group)]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass
|
|
57
|
+
class Session:
|
|
58
|
+
windows: list[Window] = field(default_factory=list)
|
|
59
|
+
browser: str = ""
|
|
60
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
61
|
+
|
|
62
|
+
def tabs(self) -> list[Tab]:
|
|
63
|
+
return [t for w in self.windows for t in w.tabs()]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
Node = Session | Window | Group | Tab
|
|
67
|
+
KINDS = {Session: "session", Window: "window", Group: "group", Tab: "tab"}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def to_dict(node: Node) -> dict:
|
|
71
|
+
d = asdict(node)
|
|
72
|
+
d["kind"] = KINDS[type(node)]
|
|
73
|
+
if isinstance(node, Window):
|
|
74
|
+
d["items"] = [to_dict(i) for i in node.items]
|
|
75
|
+
elif isinstance(node, Session):
|
|
76
|
+
d["windows"] = [to_dict(w) for w in node.windows]
|
|
77
|
+
return d
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def from_dict(d: dict) -> Node:
|
|
81
|
+
d = dict(d)
|
|
82
|
+
kind = d.pop("kind")
|
|
83
|
+
if kind == "tab":
|
|
84
|
+
return Tab(**d)
|
|
85
|
+
if kind == "group":
|
|
86
|
+
return Group(**{**d, "tabs": [from_dict({**t, "kind": "tab"}) for t in d["tabs"]]})
|
|
87
|
+
if kind == "window":
|
|
88
|
+
return Window(**{**d, "items": [from_dict(i) for i in d["items"]]})
|
|
89
|
+
if kind == "session":
|
|
90
|
+
return Session(**{**d, "windows": [from_dict(w) for w in d["windows"]]})
|
|
91
|
+
raise ValueError(f"unknown kind {kind!r}")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def dumps(node: Node) -> str:
|
|
95
|
+
return json.dumps(to_dict(node), indent=2, ensure_ascii=False) + "\n"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def loads(text: str) -> Node:
|
|
99
|
+
return from_dict(json.loads(text))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def find(session: Session, path: str) -> Node:
|
|
103
|
+
"""Resolve ``w0``, ``w0/g2`` (second-level item index), ``w0/g2/t1`` or ``w0/t3`` (flat tab index)."""
|
|
104
|
+
try:
|
|
105
|
+
parts = path.split("/")
|
|
106
|
+
node: Node = session.windows[int(parts[0][1:])]
|
|
107
|
+
for p in parts[1:]:
|
|
108
|
+
if p[0] == "g" and isinstance(node, Window):
|
|
109
|
+
node = node.items[int(p[1:])]
|
|
110
|
+
elif p[0] == "t" and isinstance(node, Window):
|
|
111
|
+
node = node.tabs()[int(p[1:])]
|
|
112
|
+
elif p[0] == "t" and isinstance(node, Group):
|
|
113
|
+
node = node.tabs[int(p[1:])]
|
|
114
|
+
else:
|
|
115
|
+
raise KeyError(path)
|
|
116
|
+
except (IndexError, ValueError):
|
|
117
|
+
raise KeyError(path) from None
|
|
118
|
+
return node
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
SCHEMA = {
|
|
122
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
123
|
+
"title": "tabwright session",
|
|
124
|
+
"description": "Ordered tree: session.windows[] > window.items[] (tab | group) > group.tabs[]. "
|
|
125
|
+
"List order is the tab-strip order and is honoured on every write path. Node paths: w0, w0/g1 "
|
|
126
|
+
"(item index of a group), w0/g1/t0 (tab inside a group), w0/t3 (flat tab index across the window).",
|
|
127
|
+
"$defs": {
|
|
128
|
+
"tab": {
|
|
129
|
+
"type": "object",
|
|
130
|
+
"required": ["kind", "url"],
|
|
131
|
+
"properties": {
|
|
132
|
+
"kind": {"const": "tab"},
|
|
133
|
+
"url": {"type": "string"},
|
|
134
|
+
"title": {"type": "string"},
|
|
135
|
+
"pinned": {"type": "boolean"},
|
|
136
|
+
"active": {"type": "boolean", "description": "the window's selected tab; at most one"},
|
|
137
|
+
"extra": {"type": "object", "description": "adapter-specific; round-tripped, never required"},
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
"group": {
|
|
141
|
+
"type": "object",
|
|
142
|
+
"required": ["kind", "tabs"],
|
|
143
|
+
"properties": {
|
|
144
|
+
"kind": {"const": "group"},
|
|
145
|
+
"title": {"type": "string"},
|
|
146
|
+
"color": {"enum": GROUP_COLORS},
|
|
147
|
+
"collapsed": {"type": "boolean"},
|
|
148
|
+
"tabs": {"type": "array", "items": {"$ref": "#/$defs/tab"}},
|
|
149
|
+
"extra": {"type": "object"},
|
|
150
|
+
},
|
|
151
|
+
},
|
|
152
|
+
"window": {
|
|
153
|
+
"type": "object",
|
|
154
|
+
"required": ["kind", "items"],
|
|
155
|
+
"properties": {
|
|
156
|
+
"kind": {"const": "window"},
|
|
157
|
+
"items": {
|
|
158
|
+
"type": "array",
|
|
159
|
+
"items": {"oneOf": [{"$ref": "#/$defs/tab"}, {"$ref": "#/$defs/group"}]},
|
|
160
|
+
},
|
|
161
|
+
"geometry": {
|
|
162
|
+
"type": ["object", "null"],
|
|
163
|
+
"properties": {
|
|
164
|
+
"x": {"type": "integer"},
|
|
165
|
+
"y": {"type": "integer"},
|
|
166
|
+
"width": {"type": "integer"},
|
|
167
|
+
"height": {"type": "integer"},
|
|
168
|
+
"state": {"enum": WINDOW_STATES},
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
"extra": {"type": "object"},
|
|
172
|
+
},
|
|
173
|
+
},
|
|
174
|
+
},
|
|
175
|
+
"type": "object",
|
|
176
|
+
"required": ["kind", "windows"],
|
|
177
|
+
"properties": {
|
|
178
|
+
"kind": {"const": "session"},
|
|
179
|
+
"browser": {"type": "string"},
|
|
180
|
+
"windows": {"type": "array", "items": {"$ref": "#/$defs/window"}},
|
|
181
|
+
"extra": {"type": "object"},
|
|
182
|
+
},
|
|
183
|
+
}
|
tabwright/native_host.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Native messaging host: launched by the browser, relays socket requests to the extension.
|
|
2
|
+
|
|
3
|
+
Wire format on stdin/stdout: uint32 native-endian length + UTF-8 JSON (Chromium's native
|
|
4
|
+
messaging). On the Unix socket: one newline-terminated JSON request per connection, one
|
|
5
|
+
newline-terminated reply. Requests are served one at a time.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import select
|
|
14
|
+
import socket
|
|
15
|
+
import struct
|
|
16
|
+
import sys
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from tabwright import live
|
|
20
|
+
|
|
21
|
+
LIMIT = 1_000_000 # Chromium rejects host->extension messages over 1 MB
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _exact(f, n: int) -> bytes:
|
|
25
|
+
buf = b""
|
|
26
|
+
while len(buf) < n:
|
|
27
|
+
chunk = f.read(n - len(buf))
|
|
28
|
+
if not chunk:
|
|
29
|
+
break
|
|
30
|
+
buf += chunk
|
|
31
|
+
return buf
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def read_msg(f):
|
|
35
|
+
head = _exact(f, 4)
|
|
36
|
+
if len(head) < 4:
|
|
37
|
+
return None
|
|
38
|
+
(n,) = struct.unpack("=I", head)
|
|
39
|
+
return json.loads(_exact(f, n))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def write_msg(f, obj) -> None:
|
|
43
|
+
data = json.dumps(obj).encode()
|
|
44
|
+
if len(data) > LIMIT:
|
|
45
|
+
raise ValueError(f"message of {len(data)} bytes exceeds the 1 MB native messaging limit")
|
|
46
|
+
f.write(struct.pack("=I", len(data)) + data)
|
|
47
|
+
f.flush()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def serve(path: Path, inp=None, out=None, log=None, ready=None) -> None:
|
|
51
|
+
# Unbuffered so select() on the fd never misses data a buffer already swallowed.
|
|
52
|
+
inp = inp or open(sys.stdin.fileno(), "rb", buffering=0) # noqa: SIM115
|
|
53
|
+
out = out or sys.stdout.buffer
|
|
54
|
+
log = log or (lambda *a: None)
|
|
55
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
56
|
+
srv = socket.socket(socket.AF_UNIX)
|
|
57
|
+
try:
|
|
58
|
+
srv.bind(str(path))
|
|
59
|
+
except OSError:
|
|
60
|
+
# A stale socket from a dead host, or a second profile of the same browser; see shortcut below.
|
|
61
|
+
probe = socket.socket(socket.AF_UNIX)
|
|
62
|
+
try:
|
|
63
|
+
probe.connect(str(path))
|
|
64
|
+
except OSError:
|
|
65
|
+
path.unlink()
|
|
66
|
+
srv.bind(str(path))
|
|
67
|
+
else:
|
|
68
|
+
# shortcut: one live profile per browser data dir, add per-profile sockets if that bites
|
|
69
|
+
probe.close()
|
|
70
|
+
log(f"{path} already served; exiting")
|
|
71
|
+
return
|
|
72
|
+
os.chmod(path, 0o600)
|
|
73
|
+
srv.listen(8)
|
|
74
|
+
log(f"listening on {path}")
|
|
75
|
+
if ready:
|
|
76
|
+
ready.set()
|
|
77
|
+
seq = 0
|
|
78
|
+
try:
|
|
79
|
+
while True:
|
|
80
|
+
ready, _, _ = select.select([inp, srv], [], [])
|
|
81
|
+
if inp in ready:
|
|
82
|
+
msg = read_msg(inp)
|
|
83
|
+
if msg is None:
|
|
84
|
+
log("stdin closed; exiting")
|
|
85
|
+
return
|
|
86
|
+
log(f"unsolicited from extension: {msg}")
|
|
87
|
+
if srv in ready:
|
|
88
|
+
conn, _ = srv.accept()
|
|
89
|
+
with conn, conn.makefile("rwb") as cf:
|
|
90
|
+
try:
|
|
91
|
+
req = json.loads(cf.readline() or b"{}")
|
|
92
|
+
seq += 1
|
|
93
|
+
write_msg(out, {**req, "id": seq})
|
|
94
|
+
while (reply := read_msg(inp)) is not None and reply.get("id") != seq:
|
|
95
|
+
log(f"skipping {reply}")
|
|
96
|
+
if reply is None:
|
|
97
|
+
cf.write(b'{"ok": false, "error": "browser disconnected"}\n')
|
|
98
|
+
cf.flush()
|
|
99
|
+
return
|
|
100
|
+
cf.write(json.dumps(reply).encode() + b"\n")
|
|
101
|
+
except Exception as e: # noqa: BLE001 - keep serving after one bad request
|
|
102
|
+
log(f"request failed: {e!r}")
|
|
103
|
+
cf.write(json.dumps({"ok": False, "error": str(e)}).encode() + b"\n")
|
|
104
|
+
cf.flush()
|
|
105
|
+
finally:
|
|
106
|
+
srv.close()
|
|
107
|
+
path.unlink(missing_ok=True)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def parent_data_dir() -> Path | None:
|
|
111
|
+
"""The browser that spawned us may run on a non-default ``--user-data-dir``; mirror its key."""
|
|
112
|
+
import re
|
|
113
|
+
|
|
114
|
+
try:
|
|
115
|
+
cmd = Path(f"/proc/{os.getppid()}/cmdline").read_bytes().replace(b"\0", b" ").decode(errors="replace")
|
|
116
|
+
except OSError:
|
|
117
|
+
return None
|
|
118
|
+
# shortcut: a data dir containing spaces is not recognised, revisit if anyone reports one
|
|
119
|
+
m = re.search(r"--user-data-dir=(\S+)", cmd)
|
|
120
|
+
return Path(m.group(1)) if m else None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def main(argv=None) -> None:
|
|
124
|
+
ap = argparse.ArgumentParser(prog="tabwright.native_host")
|
|
125
|
+
ap.add_argument("browser")
|
|
126
|
+
ap.add_argument("--data-dir", type=Path)
|
|
127
|
+
ap.add_argument("origin", nargs="*", help="extension origin and flags passed by the browser")
|
|
128
|
+
a = ap.parse_args(argv)
|
|
129
|
+
state = Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local/state")) / "tabwright"
|
|
130
|
+
state.mkdir(parents=True, exist_ok=True)
|
|
131
|
+
with open(state / "host.log", "a") as lf:
|
|
132
|
+
|
|
133
|
+
def log(s):
|
|
134
|
+
lf.write(f"{os.getpid()} {s}\n")
|
|
135
|
+
lf.flush()
|
|
136
|
+
|
|
137
|
+
data_dir = a.data_dir or parent_data_dir()
|
|
138
|
+
log(f"browser={a.browser} data_dir={data_dir}")
|
|
139
|
+
serve(live.socket_path(a.browser, data_dir), log=log)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
if __name__ == "__main__":
|
|
143
|
+
main()
|
tabwright/policy.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Managed-policy files: the durable, offline way to force or block extensions.
|
|
2
|
+
|
|
3
|
+
Both families read policy from root-owned paths, so tabwright prints the JSON and the
|
|
4
|
+
path instead of writing it. Chromium: ``ExtensionInstallForcelist`` / ``Blocklist``;
|
|
5
|
+
Firefox: ``ExtensionSettings`` in ``policies.json``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from tabwright.adapters import firefox
|
|
11
|
+
|
|
12
|
+
CHROMIUM_POLICY_DIRS = {
|
|
13
|
+
"brave": "/etc/brave/policies/managed",
|
|
14
|
+
"chrome": "/etc/opt/chrome/policies/managed",
|
|
15
|
+
"chromium": "/etc/chromium/policies/managed",
|
|
16
|
+
"edge": "/etc/opt/edge/policies/managed",
|
|
17
|
+
"vivaldi": "/etc/vivaldi/policies/managed",
|
|
18
|
+
}
|
|
19
|
+
CHROME_UPDATE_URL = "https://clients2.google.com/service/update2/crx"
|
|
20
|
+
AMO_URL = "https://addons.mozilla.org/firefox/downloads/latest/{id}/latest.xpi"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def build(browser: str, force: list[str], block: list[str]) -> tuple[dict, str]:
|
|
24
|
+
"""Return (policy JSON, install path) for ``browser``."""
|
|
25
|
+
if browser in firefox.BROWSERS:
|
|
26
|
+
settings = {
|
|
27
|
+
i: {"installation_mode": "force_installed", "install_url": AMO_URL.format(id=i)} for i in force
|
|
28
|
+
}
|
|
29
|
+
settings |= {i: {"installation_mode": "blocked"} for i in block}
|
|
30
|
+
return {"policies": {"ExtensionSettings": settings}}, "/etc/firefox/policies/policies.json"
|
|
31
|
+
pol = {}
|
|
32
|
+
if force:
|
|
33
|
+
pol["ExtensionInstallForcelist"] = [f"{i};{CHROME_UPDATE_URL}" for i in force]
|
|
34
|
+
if block:
|
|
35
|
+
pol["ExtensionInstallBlocklist"] = block
|
|
36
|
+
return pol, f"{CHROMIUM_POLICY_DIRS[browser]}/tabwright.json"
|