reviso-cli 0.1.1__tar.gz → 0.2.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.
Files changed (41) hide show
  1. {reviso_cli-0.1.1/src/reviso_cli.egg-info → reviso_cli-0.2.0}/PKG-INFO +27 -2
  2. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/README.md +22 -1
  3. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/pyproject.toml +10 -1
  4. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/__init__.py +1 -1
  5. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/cli/__init__.py +16 -27
  6. reviso_cli-0.2.0/src/reviso_cli/cli/auth.py +87 -0
  7. reviso_cli-0.2.0/src/reviso_cli/cli/credential_file.py +73 -0
  8. reviso_cli-0.2.0/src/reviso_cli/cli/credentials.py +95 -0
  9. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/cli/invites.py +4 -1
  10. reviso_cli-0.2.0/src/reviso_cli/cli/oauth_http.py +53 -0
  11. reviso_cli-0.2.0/src/reviso_cli/cli/oauth_login.py +105 -0
  12. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/local.py +6 -9
  13. {reviso_cli-0.1.1 → reviso_cli-0.2.0/src/reviso_cli.egg-info}/PKG-INFO +27 -2
  14. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli.egg-info/SOURCES.txt +8 -1
  15. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/tests/test_client.py +63 -0
  16. reviso_cli-0.2.0/tests/test_credentials.py +179 -0
  17. reviso_cli-0.2.0/tests/test_oauth_login.py +112 -0
  18. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/LICENSE +0 -0
  19. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/setup.cfg +0 -0
  20. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/__main__.py +0 -0
  21. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/access.py +0 -0
  22. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/cli/doctor.py +0 -0
  23. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/cli/guest_comments.py +0 -0
  24. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/cli/versions.py +0 -0
  25. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/client/__init__.py +0 -0
  26. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/client/collab.py +0 -0
  27. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/client/errors.py +0 -0
  28. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/client/http.py +0 -0
  29. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/client/participation.py +0 -0
  30. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/command_journal.py +0 -0
  31. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/document_route_keys.py +0 -0
  32. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/document_search.py +0 -0
  33. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/errors.py +0 -0
  34. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/ids.py +0 -0
  35. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/origin.py +0 -0
  36. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/paths.py +0 -0
  37. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli/scope.py +0 -0
  38. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli.egg-info/dependency_links.txt +0 -0
  39. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli.egg-info/entry_points.txt +0 -0
  40. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli.egg-info/requires.txt +0 -0
  41. {reviso_cli-0.1.1 → reviso_cli-0.2.0}/src/reviso_cli.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: reviso-cli
3
- Version: 0.1.1
3
+ Version: 0.2.0
4
4
  Summary: Command line client for Reviso: publish drafts for human review, read reviewer comments back, and publish revisions safely.
5
5
  License: MIT License
6
6
 
@@ -28,6 +28,10 @@ License: MIT License
28
28
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
29
  SOFTWARE.
30
30
 
31
+ Project-URL: Homepage, https://reviso.work
32
+ Project-URL: Documentation, https://github.com/reviso-si/reviso-agent
33
+ Project-URL: Repository, https://github.com/reviso-si/reviso-cli
34
+ Project-URL: Issues, https://github.com/reviso-si/reviso-cli/issues
31
35
  Keywords: reviso,review,collaboration,documents,cli,agent
32
36
  Classifier: Development Status :: 3 - Alpha
33
37
  Classifier: Environment :: Console
@@ -70,7 +74,7 @@ pull a dependency graph into an agent's environment.
70
74
 
71
75
  ```bash
72
76
  reviso auth login --server https://reviso.work
73
- # set REVISO_AUTOMATION_KEY in the environment first, or pass --key
77
+ # opens a browser for consent; use --no-browser to open the URL yourself
74
78
  reviso doctor --json
75
79
 
76
80
  reviso publish draft.md --title "Q3 launch plan" --description "Initial draft"
@@ -85,6 +89,19 @@ reviso update doc_abc123 revised.md \
85
89
  --base-version-id ver_xyz
86
90
  ```
87
91
 
92
+ ## Browser login
93
+
94
+ Version 0.2 supports browser consent with a temporary loopback callback and PKCE.
95
+ Keep the CLI running and open the login URL in a browser on the same computer.
96
+ `reviso auth status` shows the selected server and login state without credentials;
97
+ `reviso auth logout` removes that server's saved login. Revoke the connection in
98
+ Settings → Integrations to end its server access.
99
+
100
+ Credentials live in an owner-only file at `~/.config/reviso/credentials.json`
101
+ (or under `XDG_CONFIG_HOME`), separately for each server, and refresh automatically.
102
+ An existing `REVISO_AUTOMATION_KEY` or `--key` still supports headless use.
103
+ The credential lock currently supports macOS and Linux.
104
+
88
105
  ## The rule that matters
89
106
 
90
107
  **Always pass `--base-version-id` when you revise a document.**
@@ -142,3 +159,11 @@ The Reviso product itself is **not** open source. This repository covers the
142
159
  client only; it grants no rights to the service or its server software. See
143
160
  [VISIBILITY.md](VISIBILITY.md) for the boundary this repository holds, and
144
161
  [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
162
+
163
+ Publish a presentation with its explicit kind so the server validates and renders it as slides:
164
+
165
+ ```bash
166
+ reviso publish presentation.html --workspace-id <workspace-id> --kind html_deck --deck-contract-version html-deck/1
167
+ ```
168
+
169
+ Ordinary HTML keeps `--kind document` (the default); deck markup without `html_deck` is rejected by the server.
@@ -24,7 +24,7 @@ pull a dependency graph into an agent's environment.
24
24
 
25
25
  ```bash
26
26
  reviso auth login --server https://reviso.work
27
- # set REVISO_AUTOMATION_KEY in the environment first, or pass --key
27
+ # opens a browser for consent; use --no-browser to open the URL yourself
28
28
  reviso doctor --json
29
29
 
30
30
  reviso publish draft.md --title "Q3 launch plan" --description "Initial draft"
@@ -39,6 +39,19 @@ reviso update doc_abc123 revised.md \
39
39
  --base-version-id ver_xyz
40
40
  ```
41
41
 
42
+ ## Browser login
43
+
44
+ Version 0.2 supports browser consent with a temporary loopback callback and PKCE.
45
+ Keep the CLI running and open the login URL in a browser on the same computer.
46
+ `reviso auth status` shows the selected server and login state without credentials;
47
+ `reviso auth logout` removes that server's saved login. Revoke the connection in
48
+ Settings → Integrations to end its server access.
49
+
50
+ Credentials live in an owner-only file at `~/.config/reviso/credentials.json`
51
+ (or under `XDG_CONFIG_HOME`), separately for each server, and refresh automatically.
52
+ An existing `REVISO_AUTOMATION_KEY` or `--key` still supports headless use.
53
+ The credential lock currently supports macOS and Linux.
54
+
42
55
  ## The rule that matters
43
56
 
44
57
  **Always pass `--base-version-id` when you revise a document.**
@@ -96,3 +109,11 @@ The Reviso product itself is **not** open source. This repository covers the
96
109
  client only; it grants no rights to the service or its server software. See
97
110
  [VISIBILITY.md](VISIBILITY.md) for the boundary this repository holds, and
98
111
  [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
112
+
113
+ Publish a presentation with its explicit kind so the server validates and renders it as slides:
114
+
115
+ ```bash
116
+ reviso publish presentation.html --workspace-id <workspace-id> --kind html_deck --deck-contract-version html-deck/1
117
+ ```
118
+
119
+ Ordinary HTML keeps `--kind document` (the default); deck markup without `html_deck` is rejected by the server.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "reviso-cli"
7
- version = "0.1.1"
7
+ version = "0.2.0"
8
8
  description = "Command line client for Reviso: publish drafts for human review, read reviewer comments back, and publish revisions safely."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -28,6 +28,15 @@ dependencies = []
28
28
  [project.optional-dependencies]
29
29
  test = ["pytest>=8.0"]
30
30
 
31
+ # PyPI renders these as the package page's links. Without them the page is a
32
+ # dead end: someone who finds the package by search has no route to the docs,
33
+ # the source, or the issue tracker.
34
+ [project.urls]
35
+ Homepage = "https://reviso.work"
36
+ Documentation = "https://github.com/reviso-si/reviso-agent"
37
+ Repository = "https://github.com/reviso-si/reviso-cli"
38
+ Issues = "https://github.com/reviso-si/reviso-cli/issues"
39
+
31
40
  [project.scripts]
32
41
  reviso = "reviso_cli.cli:main"
33
42
 
@@ -3,6 +3,6 @@ from __future__ import annotations
3
3
 
4
4
  from .client import RevisoClient
5
5
 
6
- __version__ = "0.1.1"
6
+ __version__ = "0.2.0"
7
7
 
8
8
  __all__ = ["RevisoClient", "__version__"]
@@ -3,7 +3,6 @@ from __future__ import annotations
3
3
 
4
4
  import argparse
5
5
  import json
6
- import os
7
6
  from pathlib import Path
8
7
 
9
8
  from .. import command_journal
@@ -16,6 +15,9 @@ from ..origin import DEFAULT_SERVER_URL
16
15
  from ..paths import config_path, packet_path, read_json, write_json
17
16
  from ..scope import resolve_agent_create_scope
18
17
  from .doctor import doctor_report, print_doctor
18
+ from .auth import AuthenticatedClient, auth_command
19
+ from .credentials import access_token, selected_server
20
+ from .oauth_http import server_origin
19
21
  from .guest_comments import add_guest_comment_commands
20
22
  from .invites import add_invite_commands
21
23
  from .versions import add_version_commands, format_file_arg
@@ -33,38 +35,19 @@ def _load_config() -> dict:
33
35
 
34
36
 
35
37
  def _server_url() -> str:
36
- cfg = _load_config()
37
- return os.environ.get("REVISO_SERVER",
38
- cfg.get("server", DEFAULT_SERVER_URL))
38
+ return server_origin(selected_server(_load_config()) or DEFAULT_SERVER_URL)
39
39
 
40
40
 
41
41
  def _automation_key(cfg: dict) -> str:
42
- return (os.environ.get("REVISO_AUTOMATION_KEY")
43
- or cfg.get("automation_key", ""))
42
+ return access_token(_server_url(), cfg)
44
43
 
45
44
 
46
45
  def _client() -> RevisoClient:
47
- return RevisoClient(_server_url(), _automation_key(_load_config()) or None)
46
+ return AuthenticatedClient(_server_url(), None, _load_config())
48
47
 
49
48
 
50
49
  def cmd_auth(args: argparse.Namespace) -> None:
51
- if args.action == "login":
52
- key = args.key or os.environ.get("REVISO_AUTOMATION_KEY", "")
53
- server = args.server or os.environ.get("REVISO_SERVER",
54
- DEFAULT_SERVER_URL)
55
- if not key:
56
- print("No automation key. Create one in Reviso under Settings -> "
57
- "Integrations, then set REVISO_AUTOMATION_KEY or pass --key.")
58
- return
59
- write_json(config_path(), {"server": server, "automation_key": key})
60
- print(f"Saved to {config_path()}")
61
- elif args.action == "status":
62
- cfg = _load_config()
63
- print(f"server: {cfg.get('server', '(not set)')}")
64
- print(f"key: {'set' if cfg.get('automation_key') else '(not set)'}")
65
- print(f"config: {config_path()}")
66
- else:
67
- print(f"unknown auth action: {args.action}")
50
+ auth_command(args, _load_config())
68
51
 
69
52
 
70
53
  def cmd_publish(args: argparse.Namespace) -> None:
@@ -73,15 +56,18 @@ def cmd_publish(args: argparse.Namespace) -> None:
73
56
  content = path.read_text()
74
57
  fmt = format_file_arg(args, path)
75
58
  title = args.title or path.name
59
+ kind, contract = args.kind, args.deck_contract_version
60
+ options = {key: value for key, value in (("document_kind", kind), ("deck_contract_version", contract)) if value is not None}
76
61
  # A journaled operation_id is reused across reruns of THIS command, so a
77
62
  # crashed-then-rerun publish replays instead of double-creating. Cleared
78
63
  # only after every local success step has completed.
79
64
  parts = [title, content, fmt, args.description or "",
80
65
  scope.workspace_id, scope.parent_id]
66
+ if options: parts.extend([kind or "", contract or ""])
81
67
  op = command_journal.operation_id_for("publish", parts)
82
68
  result = _client().publish(title, content, fmt, args.description,
83
69
  scope.workspace_id, scope.parent_id,
84
- operation_id=op)
70
+ operation_id=op, **options)
85
71
  mapping = write_mapping(result, path)
86
72
  print(mapping["url"])
87
73
  command_journal.forget("publish", parts)
@@ -172,14 +158,15 @@ def _workspace_scope(explicit: str = "", parent_id: str = ""):
172
158
  key = _automation_key(cfg)
173
159
  return resolve_agent_create_scope(
174
160
  explicit_workspace_id=explicit, explicit_parent_id=parent_id,
175
- config=cfg, has_automation_key=key.startswith("rak_"))
161
+ config=cfg, has_automation_key=bool(key))
176
162
 
177
163
 
178
164
  def _add_basic(sub: argparse._SubParsersAction) -> None:
179
165
  auth = sub.add_parser("auth")
180
- auth.add_argument("action", nargs="?", default="login")
166
+ auth.add_argument("action", nargs="?", default="login", choices=["login", "status", "logout"])
181
167
  auth.add_argument("--server")
182
168
  auth.add_argument("--key")
169
+ auth.add_argument("--no-browser", action="store_true", help="Print the login URL without opening a browser.")
183
170
  auth.set_defaults(func=cmd_auth)
184
171
  pub = sub.add_parser("publish")
185
172
  pub.add_argument("file")
@@ -188,6 +175,8 @@ def _add_basic(sub: argparse._SubParsersAction) -> None:
188
175
  pub.add_argument("--description", default="Initial draft")
189
176
  pub.add_argument("--workspace-id", default="")
190
177
  pub.add_argument("--parent-id", default="")
178
+ pub.add_argument("--kind", choices=["document", "html_deck"])
179
+ pub.add_argument("--deck-contract-version")
191
180
  pub.set_defaults(func=cmd_publish)
192
181
  opn = sub.add_parser("open")
193
182
  opn.add_argument("document_id")
@@ -0,0 +1,87 @@
1
+ """CLI login and status use the same origin/credential resolution as commands."""
2
+ import os
3
+ import time
4
+
5
+ from ..client import RevisoClient
6
+ from .credential_file import credential_path, read_credentials
7
+ from .credentials import (
8
+ LOGIN_HINT,
9
+ access_token,
10
+ forget_login,
11
+ legacy_token,
12
+ save_login,
13
+ selected_server,
14
+ server_sources,
15
+ )
16
+ from .oauth_http import server_origin
17
+ from .oauth_login import browser_login
18
+
19
+
20
+ class AuthenticatedClient(RevisoClient):
21
+ def __init__(self, server, key, config):
22
+ super().__init__(server, key)
23
+ self._config = config
24
+
25
+ def _request(self, method, path, **kwargs):
26
+ public = path in {"/healthz", "/readyz", "/version"}
27
+ guest = kwargs.get("guest_id") and kwargs.get("guest_token")
28
+ self._key = None if public or guest else access_token(self.url, self._config) or None
29
+ return super()._request(method, path, **kwargs)
30
+
31
+
32
+ def auth_command(args, legacy):
33
+ server = selected_server(legacy, args.server)
34
+ server = server_origin(server) if server else ""
35
+ if args.action == "status":
36
+ return _status(server, legacy, args.server)
37
+ if args.action == "logout":
38
+ forget_login(server)
39
+ print("Removed saved login for this server. Revoke the connection in Settings > Integrations.")
40
+ if os.environ.get("REVISO_AUTOMATION_KEY") or legacy_token(legacy, server):
41
+ print("An environment or legacy project key still exists; remove it separately.")
42
+ return
43
+ server = server or "https://reviso.work"
44
+ key = args.key or os.environ.get("REVISO_AUTOMATION_KEY", "")
45
+ if key:
46
+ RevisoClient(server, key)._request("GET", "/api/agent-connection/self")
47
+ save_login(server, {"access_token": key})
48
+ else:
49
+ previous = read_credentials().get("servers", {}).get(server, {})
50
+ browser_login(server, previous, no_browser=getattr(args, "no_browser", False))
51
+ print(f"Logged in to {server}. Credentials saved privately at {credential_path()}.")
52
+
53
+
54
+ def _status(server, legacy, explicit=""):
55
+ sources = server_sources(legacy, explicit)
56
+ selected = next((key for key, value in sources.items() if value), "none")
57
+ print(f"server: {server or '(not configured)'}")
58
+ print(f"server_source: {selected}")
59
+ for key, value in sources.items():
60
+ print(f"server_{key}: {_display_server(value)}")
61
+ if not server:
62
+ print(LOGIN_HINT)
63
+ return
64
+ entry = read_credentials().get("servers", {}).get(server.rstrip("/"), {})
65
+ if os.environ.get("REVISO_AUTOMATION_KEY"):
66
+ state = "environment key (not checked with server)"
67
+ elif entry.get("reauth_required"):
68
+ state = "login required; " + LOGIN_HINT
69
+ elif entry.get("refresh_token"):
70
+ state = "OAuth saved; refresh due" if entry.get("expires_at", 0) <= time.time() + 60 else "OAuth saved"
71
+ elif entry.get("client_id") and entry.get("expires_at"):
72
+ state = "login required; " + LOGIN_HINT if entry["expires_at"] <= time.time() else "OAuth saved; server has no refresh support"
73
+ elif entry.get("access_token") or legacy_token(legacy, server):
74
+ state = "saved key (not checked with server)"
75
+ else:
76
+ state = "not logged in; " + LOGIN_HINT
77
+ print(f"auth: {state}")
78
+ print(f"credentials: {credential_path()}")
79
+
80
+
81
+ def _display_server(value):
82
+ if not value:
83
+ return "(not set)"
84
+ try:
85
+ return server_origin(value)
86
+ except ValueError:
87
+ return "(invalid server origin)"
@@ -0,0 +1,73 @@
1
+ """User-level credential storage, independent of the current checkout."""
2
+ import fcntl
3
+ import json
4
+ import os
5
+ import stat
6
+ import tempfile
7
+ import time
8
+ from contextlib import contextmanager
9
+ from pathlib import Path
10
+
11
+
12
+ def credential_path() -> Path:
13
+ root = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
14
+ if not root.is_absolute():
15
+ raise ValueError("XDG_CONFIG_HOME must be an absolute path.")
16
+ return root / "reviso" / "credentials.json"
17
+
18
+
19
+ def read_credentials() -> dict:
20
+ try:
21
+ fd = os.open(credential_path(), os.O_RDONLY | os.O_NOFOLLOW)
22
+ except FileNotFoundError:
23
+ return {}
24
+ with os.fdopen(fd) as stream:
25
+ info = os.fstat(stream.fileno())
26
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
27
+ raise ValueError("Reviso credentials must be an owner-only regular file (chmod 600).")
28
+ data = json.load(stream)
29
+ if not isinstance(data, dict) or not isinstance(data.get("servers", {}), dict):
30
+ raise ValueError("Invalid Reviso credentials file; repair or remove it before login.")
31
+ return data
32
+
33
+
34
+ @contextmanager
35
+ def credential_lock():
36
+ path = credential_path()
37
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
38
+ info = path.parent.lstat()
39
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o022:
40
+ raise ValueError("Reviso credential directory must be owned and writable only by you.")
41
+ fd = os.open(path.with_suffix(".lock"), os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
42
+ try:
43
+ deadline = time.monotonic() + 30
44
+ while True:
45
+ try:
46
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
47
+ break
48
+ except BlockingIOError:
49
+ if time.monotonic() >= deadline:
50
+ raise TimeoutError("Another Reviso process is updating credentials; retry.") from None
51
+ time.sleep(0.05)
52
+ yield
53
+ finally:
54
+ os.close(fd)
55
+
56
+
57
+ def write_credentials(data: dict) -> None:
58
+ path = credential_path()
59
+ fd, name = tempfile.mkstemp(prefix=".credentials-", dir=path.parent)
60
+ try:
61
+ with os.fdopen(fd, "w") as stream:
62
+ json.dump(data, stream)
63
+ stream.flush()
64
+ os.fsync(stream.fileno())
65
+ os.replace(name, path)
66
+ directory = os.open(path.parent, os.O_RDONLY)
67
+ try:
68
+ os.fsync(directory)
69
+ finally:
70
+ os.close(directory)
71
+ finally:
72
+ if os.path.exists(name):
73
+ os.unlink(name)
@@ -0,0 +1,95 @@
1
+ """Resolve and refresh only the credentials belonging to the selected origin."""
2
+ import os
3
+ import time
4
+
5
+ from .credential_file import credential_lock, read_credentials, write_credentials
6
+ from .oauth_http import OAuthFailure, oauth_json, server_origin
7
+
8
+ LOGIN_HINT = "Run reviso auth login --server https://reviso.work (or your configured server)."
9
+
10
+
11
+ def server_sources(legacy: dict, explicit: str = "") -> dict:
12
+ return {"argument": explicit or "", "environment": os.environ.get("REVISO_SERVER", ""),
13
+ "project_config": legacy.get("server", ""),
14
+ "user_config": read_credentials().get("server", "")}
15
+
16
+
17
+ def selected_server(legacy: dict, explicit: str = "") -> str:
18
+ return next((value for value in server_sources(legacy, explicit).values() if value), "")
19
+
20
+
21
+ def legacy_token(legacy: dict, server: str) -> str:
22
+ bound = str(legacy.get("server") or "").rstrip("/")
23
+ return legacy.get("automation_key", "") if bound == server.rstrip("/") else ""
24
+
25
+
26
+ def access_token(server: str, legacy: dict) -> str:
27
+ explicit = os.environ.get("REVISO_AUTOMATION_KEY")
28
+ if explicit:
29
+ return explicit
30
+ server = server.rstrip("/")
31
+ if server not in read_credentials().get("servers", {}):
32
+ return legacy_token(legacy, server)
33
+ with credential_lock():
34
+ data = read_credentials()
35
+ entry = data.get("servers", {}).get(server, {})
36
+ if entry.get("reauth_required"):
37
+ raise OAuthFailure("login_required")
38
+ token = entry.get("access_token", "")
39
+ if not entry.get("refresh_token"):
40
+ if entry.get("expires_at") and time.time() >= entry["expires_at"]:
41
+ raise OAuthFailure("login_required")
42
+ return token
43
+ if time.time() < entry.get("expires_at", 0) - 60:
44
+ return token
45
+ # Persist the in-flight state before sending a single-use credential.
46
+ # After a crash/ambiguous timeout, login again instead of replaying it.
47
+ entry["reauth_required"] = True
48
+ write_credentials(data)
49
+ try:
50
+ payload = oauth_json(server_origin(server) + "/oauth/token", {
51
+ "grant_type": "refresh_token", "refresh_token": entry["refresh_token"],
52
+ "client_id": entry["client_id"], "resource": server + "/mcp"}, form=True)
53
+ except OAuthFailure as exc:
54
+ if exc.oauth_code == "rate_limited":
55
+ entry.pop("reauth_required", None)
56
+ write_credentials(data)
57
+ raise
58
+ entry.update(token_fields(payload, require_refresh=True))
59
+ entry.pop("reauth_required", None)
60
+ write_credentials(data)
61
+ return entry["access_token"]
62
+
63
+
64
+ def token_fields(payload: dict, *, require_refresh: bool = True) -> dict:
65
+ if (not isinstance(payload.get("access_token"), str)
66
+ or not payload["access_token"]
67
+ or payload.get("token_type", "").lower() != "bearer"
68
+ or not isinstance(payload.get("expires_in"), (int, float))
69
+ or not 0 < payload["expires_in"] <= 31536000):
70
+ raise OAuthFailure("invalid_token_response")
71
+ refresh = payload.get("refresh_token")
72
+ if (require_refresh or refresh is not None) and (not isinstance(refresh, str) or not refresh):
73
+ raise OAuthFailure("invalid_token_response")
74
+ result = {"access_token": payload["access_token"],
75
+ "expires_at": time.time() + payload["expires_in"]}
76
+ if refresh:
77
+ result.update(refresh_token=refresh, refresh_expires_at=payload.get("refresh_expires_at", ""))
78
+ return result
79
+
80
+
81
+ def save_login(server: str, entry: dict) -> None:
82
+ with credential_lock():
83
+ data = read_credentials()
84
+ data.setdefault("servers", {})[server] = entry
85
+ data["server"] = server
86
+ write_credentials(data)
87
+
88
+
89
+ def forget_login(server: str) -> None:
90
+ with credential_lock():
91
+ data = read_credentials()
92
+ data.get("servers", {}).pop(server, None)
93
+ if data.get("server") == server:
94
+ data.pop("server", None)
95
+ write_credentials(data)
@@ -47,7 +47,10 @@ def _create(args: argparse.Namespace,
47
47
  if args.json:
48
48
  print(json.dumps(result, indent=2, sort_keys=True))
49
49
  return
50
- if result.get("existing"):
50
+ if result.get("account_shared"):
51
+ label = "account share updated" if result.get("existing") else "shared with account"
52
+ print(f"{label}: {result['grant_id']}")
53
+ elif result.get("existing"):
51
54
  print(f"pending invite already exists: {result['invite_id']}")
52
55
  else:
53
56
  print(result.get("invite_url") or result["invite_id"])
@@ -0,0 +1,53 @@
1
+ """Bounded OAuth HTTP requests without redirects or credential-bearing errors."""
2
+ import json
3
+ import urllib.error
4
+ import urllib.request
5
+ from urllib.parse import urlencode, urlsplit
6
+
7
+ class OAuthFailure(SystemExit):
8
+ def __init__(self, code: str):
9
+ self.oauth_code = code
10
+ super().__init__(f"OAuth {code}. Run reviso auth login --server <your-server> to retry.")
11
+
12
+
13
+ class NoRedirect(urllib.request.HTTPRedirectHandler):
14
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
15
+ raise OAuthFailure("unexpected_redirect")
16
+
17
+
18
+ def server_origin(value: str) -> str:
19
+ parsed = urlsplit(value)
20
+ if (parsed.scheme not in ("https", "http") or not parsed.hostname
21
+ or parsed.username or parsed.password or parsed.query or parsed.fragment
22
+ or parsed.path not in ("", "/")
23
+ or any(c.isspace() or c == "\\" for c in value)):
24
+ raise ValueError("--server must be an HTTPS origin (HTTP is allowed only on loopback).")
25
+ if parsed.scheme == "http" and parsed.hostname not in ("localhost", "127.0.0.1", "::1"):
26
+ raise ValueError("Use HTTPS for hosted Reviso; HTTP credentials are restricted to loopback.")
27
+ if parsed.port is not None and not 1 <= parsed.port <= 65535:
28
+ raise ValueError("Invalid server port")
29
+ return f"{parsed.scheme}://{parsed.netloc.lower()}".rstrip("/")
30
+
31
+
32
+ def oauth_json(url: str, body: dict | None = None, *, form=False) -> dict:
33
+ data = (urlencode(body).encode() if form else json.dumps(body).encode()) if body is not None else None
34
+ req = urllib.request.Request(url, data=data, headers={
35
+ "Accept": "application/json", "Content-Type":
36
+ "application/x-www-form-urlencoded" if form else "application/json"})
37
+ try:
38
+ with urllib.request.build_opener(NoRedirect).open(req, timeout=15) as response:
39
+ payload = json.loads(response.read(1024 * 1024))
40
+ except urllib.error.HTTPError as exc:
41
+ if exc.code == 429:
42
+ raise OAuthFailure("rate_limited") from None
43
+ try:
44
+ error = json.loads(exc.read(4096)).get("error")
45
+ except (ValueError, AttributeError):
46
+ error = "http_error"
47
+ allowed = {"invalid_grant", "invalid_client", "invalid_request", "invalid_scope", "access_denied"}
48
+ raise OAuthFailure(error if error in allowed else "http_error") from None
49
+ except (urllib.error.URLError, TimeoutError, ValueError):
50
+ raise OAuthFailure("unavailable_or_invalid_response") from None
51
+ if not isinstance(payload, dict) or payload.get("error"):
52
+ raise OAuthFailure("invalid_response")
53
+ return payload
@@ -0,0 +1,105 @@
1
+ """Browser authorization using a temporary loopback listener, state and PKCE."""
2
+ import hashlib
3
+ import secrets
4
+ import time
5
+ import webbrowser
6
+ from base64 import urlsafe_b64encode
7
+ from http.server import BaseHTTPRequestHandler, HTTPServer
8
+ from urllib.parse import parse_qs, urlencode, urlsplit
9
+
10
+ from .credentials import save_login, token_fields
11
+ from .oauth_http import OAuthFailure, oauth_json
12
+
13
+
14
+ class LoopbackServer(HTTPServer):
15
+ def get_request(self):
16
+ connection, address = super().get_request()
17
+ connection.settimeout(2)
18
+ return connection, address
19
+
20
+
21
+ def _handler(state: str, result: dict):
22
+ class Callback(BaseHTTPRequestHandler):
23
+ def do_GET(self):
24
+ parsed = urlsplit(self.path)
25
+ params = parse_qs(parsed.query)
26
+ valid = (parsed.path == "/callback" and len(params.get("state", [])) == 1
27
+ and secrets.compare_digest(params["state"][0], state))
28
+ code = params.get("code", [])
29
+ error = params.get("error", [])
30
+ valid = valid and ((len(code) == 1 and not error) or (len(error) == 1 and not code))
31
+ if valid:
32
+ result.update(code=code[0] if code else "", error=bool(error))
33
+ self.send_response(200 if valid else 400)
34
+ self.send_header("Content-Type", "text/plain; charset=utf-8")
35
+ self.send_header("Cache-Control", "no-store")
36
+ self.end_headers()
37
+ self.wfile.write(b"Authorization received. Return to the Reviso CLI to confirm login."
38
+ if valid else b"Invalid callback. Return to the Reviso CLI and retry.")
39
+
40
+ def log_message(self, format, *args):
41
+ pass
42
+ return Callback
43
+
44
+
45
+ def _metadata(server: str) -> dict:
46
+ data = oauth_json(server + "/.well-known/oauth-authorization-server")
47
+ for field, path in (("authorization_endpoint", "/oauth/authorize"),
48
+ ("token_endpoint", "/oauth/token"),
49
+ ("registration_endpoint", "/oauth/register")):
50
+ if data.get(field) != server + path:
51
+ raise OAuthFailure("endpoint_origin_mismatch")
52
+ if data.get("issuer") != server or "S256" not in data.get("code_challenge_methods_supported", []):
53
+ raise OAuthFailure("unsupported_server")
54
+ return data
55
+
56
+
57
+ def browser_login(server: str, previous: dict, *, timeout: float = 180, no_browser=False) -> dict:
58
+ metadata = _metadata(server)
59
+ state, verifier = secrets.token_urlsafe(32), secrets.token_urlsafe(48)
60
+ result = {}
61
+ port = urlsplit(previous.get("redirect_uri", "")).port or 0
62
+ try:
63
+ listener = LoopbackServer(("127.0.0.1", port), _handler(state, result))
64
+ except OSError:
65
+ listener = LoopbackServer(("127.0.0.1", 0), _handler(state, result))
66
+ with listener:
67
+ listener.timeout = 0.25
68
+ redirect = f"http://127.0.0.1:{listener.server_port}/callback"
69
+ client_id = _register(metadata, previous, redirect)
70
+ challenge = urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=")
71
+ query = {"response_type": "code", "client_id": client_id, "redirect_uri": redirect,
72
+ "resource": server + "/mcp", "scope": "mcp", "state": state,
73
+ "code_challenge": challenge, "code_challenge_method": "S256", "client_kind": "cli"}
74
+ url = metadata["authorization_endpoint"] + "?" + urlencode(query)
75
+ print("Open this URL to sign in (waiting up to " + str(int(timeout)) + " seconds):\n" + url, flush=True)
76
+ if not no_browser:
77
+ try:
78
+ webbrowser.open(url)
79
+ except webbrowser.Error:
80
+ print("Browser could not open; use the URL above on this machine.", flush=True)
81
+ deadline = time.monotonic() + timeout
82
+ while not result and time.monotonic() < deadline:
83
+ listener.handle_request()
84
+ if not result or result.get("error"):
85
+ raise OAuthFailure("access_denied" if result else "callback_timeout")
86
+ payload = oauth_json(metadata["token_endpoint"], {
87
+ "grant_type": "authorization_code", "client_id": client_id,
88
+ "redirect_uri": redirect, "resource": server + "/mcp",
89
+ "code": result["code"], "code_verifier": verifier}, form=True)
90
+ fields = token_fields(payload, require_refresh="refresh_token" in metadata.get("grant_types_supported", []))
91
+ entry = {"client_id": client_id, "redirect_uri": redirect, **fields}
92
+ save_login(server, entry)
93
+ return entry
94
+
95
+
96
+ def _register(metadata: dict, previous: dict, redirect: str) -> str:
97
+ if previous.get("client_id") and previous.get("redirect_uri") == redirect:
98
+ return previous["client_id"]
99
+ result = oauth_json(metadata["registration_endpoint"], {
100
+ "client_name": "Reviso CLI", "redirect_uris": [redirect],
101
+ "grant_types": ["authorization_code", "refresh_token"],
102
+ "response_types": ["code"], "token_endpoint_auth_method": "none"})
103
+ if not isinstance(result.get("client_id"), str) or not result["client_id"]:
104
+ raise OAuthFailure("invalid_registration_response")
105
+ return result["client_id"]
@@ -1,7 +1,6 @@
1
1
  """Local mapping management — no Store imports, HTTP-only."""
2
2
  from __future__ import annotations
3
3
 
4
- import os
5
4
  import subprocess
6
5
  from pathlib import Path
7
6
 
@@ -12,14 +11,12 @@ from .paths import config_path, mapping_path, read_json, write_json
12
11
 
13
12
 
14
13
  def _server_url() -> str:
15
- env = os.environ.get("REVISO_SERVER")
16
- if env:
17
- return env
18
- cfg_path = config_path()
19
- if cfg_path.exists():
20
- cfg = read_json(cfg_path)
21
- return cfg.get("server", DEFAULT_SERVER_URL)
22
- return DEFAULT_SERVER_URL
14
+ from .cli.credentials import selected_server
15
+ from .cli.oauth_http import server_origin
16
+
17
+ path = config_path()
18
+ cfg = read_json(path) if path.exists() else {}
19
+ return server_origin(selected_server(cfg) or DEFAULT_SERVER_URL)
23
20
 
24
21
 
25
22
  def write_mapping(result: dict, file_path: Path) -> dict:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: reviso-cli
3
- Version: 0.1.1
3
+ Version: 0.2.0
4
4
  Summary: Command line client for Reviso: publish drafts for human review, read reviewer comments back, and publish revisions safely.
5
5
  License: MIT License
6
6
 
@@ -28,6 +28,10 @@ License: MIT License
28
28
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
29
  SOFTWARE.
30
30
 
31
+ Project-URL: Homepage, https://reviso.work
32
+ Project-URL: Documentation, https://github.com/reviso-si/reviso-agent
33
+ Project-URL: Repository, https://github.com/reviso-si/reviso-cli
34
+ Project-URL: Issues, https://github.com/reviso-si/reviso-cli/issues
31
35
  Keywords: reviso,review,collaboration,documents,cli,agent
32
36
  Classifier: Development Status :: 3 - Alpha
33
37
  Classifier: Environment :: Console
@@ -70,7 +74,7 @@ pull a dependency graph into an agent's environment.
70
74
 
71
75
  ```bash
72
76
  reviso auth login --server https://reviso.work
73
- # set REVISO_AUTOMATION_KEY in the environment first, or pass --key
77
+ # opens a browser for consent; use --no-browser to open the URL yourself
74
78
  reviso doctor --json
75
79
 
76
80
  reviso publish draft.md --title "Q3 launch plan" --description "Initial draft"
@@ -85,6 +89,19 @@ reviso update doc_abc123 revised.md \
85
89
  --base-version-id ver_xyz
86
90
  ```
87
91
 
92
+ ## Browser login
93
+
94
+ Version 0.2 supports browser consent with a temporary loopback callback and PKCE.
95
+ Keep the CLI running and open the login URL in a browser on the same computer.
96
+ `reviso auth status` shows the selected server and login state without credentials;
97
+ `reviso auth logout` removes that server's saved login. Revoke the connection in
98
+ Settings → Integrations to end its server access.
99
+
100
+ Credentials live in an owner-only file at `~/.config/reviso/credentials.json`
101
+ (or under `XDG_CONFIG_HOME`), separately for each server, and refresh automatically.
102
+ An existing `REVISO_AUTOMATION_KEY` or `--key` still supports headless use.
103
+ The credential lock currently supports macOS and Linux.
104
+
88
105
  ## The rule that matters
89
106
 
90
107
  **Always pass `--base-version-id` when you revise a document.**
@@ -142,3 +159,11 @@ The Reviso product itself is **not** open source. This repository covers the
142
159
  client only; it grants no rights to the service or its server software. See
143
160
  [VISIBILITY.md](VISIBILITY.md) for the boundary this repository holds, and
144
161
  [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
162
+
163
+ Publish a presentation with its explicit kind so the server validates and renders it as slides:
164
+
165
+ ```bash
166
+ reviso publish presentation.html --workspace-id <workspace-id> --kind html_deck --deck-contract-version html-deck/1
167
+ ```
168
+
169
+ Ordinary HTML keeps `--kind document` (the default); deck markup without `html_deck` is rejected by the server.
@@ -20,13 +20,20 @@ src/reviso_cli.egg-info/entry_points.txt
20
20
  src/reviso_cli.egg-info/requires.txt
21
21
  src/reviso_cli.egg-info/top_level.txt
22
22
  src/reviso_cli/cli/__init__.py
23
+ src/reviso_cli/cli/auth.py
24
+ src/reviso_cli/cli/credential_file.py
25
+ src/reviso_cli/cli/credentials.py
23
26
  src/reviso_cli/cli/doctor.py
24
27
  src/reviso_cli/cli/guest_comments.py
25
28
  src/reviso_cli/cli/invites.py
29
+ src/reviso_cli/cli/oauth_http.py
30
+ src/reviso_cli/cli/oauth_login.py
26
31
  src/reviso_cli/cli/versions.py
27
32
  src/reviso_cli/client/__init__.py
28
33
  src/reviso_cli/client/collab.py
29
34
  src/reviso_cli/client/errors.py
30
35
  src/reviso_cli/client/http.py
31
36
  src/reviso_cli/client/participation.py
32
- tests/test_client.py
37
+ tests/test_client.py
38
+ tests/test_credentials.py
39
+ tests/test_oauth_login.py
@@ -146,3 +146,66 @@ def test_same_origin_redirect_is_still_followed(server):
146
146
  assert _client(server).health() == {"status": "ok"}
147
147
  assert [call["path"] for call in server.calls] == ["/healthz", "/moved"]
148
148
  assert server.calls[-1]["authorization"] == "Bearer rak_test"
149
+
150
+
151
+ @pytest.mark.parametrize("existing", [False, True])
152
+ def test_invite_cli_formats_account_share_without_invite_id(server, existing, capsys):
153
+ from argparse import Namespace
154
+ from reviso_cli.cli.invites import _create
155
+
156
+ server.routes["/api/documents/doc_1/invites"] = (
157
+ 200 if existing else 201,
158
+ {"account_shared": True, "review_id": "doc_1", "grant_id": "test-grant", "existing": existing}, "")
159
+ _create(Namespace(document_id="doc_1", email="reader@example.test", access="comment", json=False),
160
+ lambda: _client(server))
161
+ label = "account share updated" if existing else "shared with account"
162
+ assert capsys.readouterr().out.strip() == f"{label}: test-grant"
163
+ assert server.calls[-1]["body"] == {"email": "reader@example.test", "access": "comment"}
164
+
165
+
166
+ @pytest.mark.parametrize("kind", [None, "document", "html_deck"])
167
+ def test_publish_cli_preserves_explicit_document_kind(server, monkeypatch, tmp_path, kind):
168
+ from reviso_cli import cli
169
+
170
+ origin = f"http://127.0.0.1:{server.server_port}"
171
+ monkeypatch.setenv('REVISO_SERVER', origin)
172
+ monkeypatch.setenv('REVISO_AUTOMATION_KEY', 'test-automation')
173
+ monkeypatch.setenv('REVISO_STATE_DIR', str(tmp_path / 'state'))
174
+ monkeypatch.setenv('XDG_CONFIG_HOME', str(tmp_path / 'config'))
175
+ server.routes['/api/documents'] = (201, {'document_id': 'doc_0123456789ab', 'version_id': 'ver_1'}, '')
176
+ file = tmp_path / 'presentation.html'
177
+ file.write_text('<div class="hr-deck">Test</div>' if kind == 'html_deck' else '<p>Ordinary HTML</p>')
178
+ args = ['publish', str(file), '--workspace-id', 'wsp_test']
179
+ if kind:
180
+ args += ['--kind', kind]
181
+ if kind == 'html_deck':
182
+ args += ['--deck-contract-version', 'html-deck/1']
183
+ cli.main(args)
184
+ call, = server.calls
185
+ assert call['method'] == 'POST' and call['path'] == '/api/documents'
186
+ assert call['body']['content'] == file.read_text()
187
+ assert call['body']['source_format'] == 'html'
188
+ assert call['body'].get('document_kind') == kind
189
+ assert call['body'].get('deck_contract_version') == ('html-deck/1' if kind == 'html_deck' else None)
190
+ mapping = json.loads((tmp_path / 'state/reviews/doc_0123456789ab.json').read_text())
191
+ assert mapping['base_server_version_id'] == 'ver_1'
192
+ assert mapping['url'] == origin + '/documents/0123456789ab'
193
+
194
+
195
+ def test_publish_retries_bind_the_explicit_deck_kind(server, monkeypatch, tmp_path):
196
+ from reviso_cli import cli
197
+
198
+ monkeypatch.setenv('REVISO_SERVER', f'http://127.0.0.1:{server.server_port}')
199
+ monkeypatch.setenv('REVISO_AUTOMATION_KEY', 'test-automation')
200
+ monkeypatch.setenv('REVISO_STATE_DIR', str(tmp_path / 'state'))
201
+ monkeypatch.setenv('XDG_CONFIG_HOME', str(tmp_path / 'config'))
202
+ server.routes['/api/documents'] = (400, {'error': {'code': 'VALIDATION_ERROR', 'message': 'rejected'}}, '')
203
+ file = tmp_path / 'deck.html'
204
+ file.write_text('<div class="hr-deck">Test</div>')
205
+ args = ['publish', str(file), '--workspace-id', 'wsp_test']
206
+ for flags in ([], ['--kind', 'html_deck'], ['--kind', 'html_deck']):
207
+ with pytest.raises(SystemExit, match='VALIDATION_ERROR'):
208
+ cli.main(args + flags)
209
+ plain, deck, retry = [call['body']['operation_id'] for call in server.calls]
210
+ assert plain != deck
211
+ assert deck == retry
@@ -0,0 +1,179 @@
1
+ # ruff: noqa: S105 # credential fixtures, never real tokens
2
+ """Persistence, origin isolation and concurrent refresh through the real CLI path."""
3
+ import io
4
+ import json
5
+ import os
6
+ import time
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from types import SimpleNamespace
9
+
10
+ import pytest
11
+
12
+ from reviso_cli import cli
13
+ from reviso_cli.cli import credentials
14
+ from reviso_cli.cli.credential_file import credential_path, read_credentials
15
+ from reviso_cli.cli.oauth_http import OAuthFailure
16
+ from reviso_cli.client import http
17
+
18
+ SERVER = "https://reviso.test"
19
+
20
+
21
+ @pytest.fixture(autouse=True)
22
+ def isolated(monkeypatch, tmp_path):
23
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config"))
24
+ monkeypatch.setenv("REVISO_STATE_DIR", str(tmp_path / "state"))
25
+ monkeypatch.delenv("REVISO_SERVER", raising=False)
26
+ monkeypatch.delenv("REVISO_AUTOMATION_KEY", raising=False)
27
+ def request(req, **kwargs):
28
+ return io.BytesIO(json.dumps({"authorization": req.get_header("Authorization")}).encode())
29
+ monkeypatch.setattr(http.urllib.request, "build_opener", lambda *a: SimpleNamespace(open=request))
30
+
31
+
32
+ def saved(**overrides):
33
+ return {"access_token": "test-old", "refresh_token": "test-old", "client_id": "test-one",
34
+ "expires_at": time.time() - 1, **overrides}
35
+
36
+
37
+ def fresh():
38
+ return {"access_token": "test-new", "refresh_token": "test-new", "expires_in": 3600,
39
+ "token_type": "Bearer", "refresh_expires_at": "2099-01-01T00:00:00Z"}
40
+
41
+
42
+ def test_login_survives_directory_change_and_never_prints_keys(monkeypatch, tmp_path, capsys):
43
+ credentials.save_login(SERVER, saved(expires_at=time.time() + 3600))
44
+ other = tmp_path / "another-project"
45
+ other.mkdir()
46
+ monkeypatch.chdir(other)
47
+ assert cli._server_url() == SERVER
48
+ assert cli._client().workspaces()["authorization"] == "Bearer test-old"
49
+ cli.cmd_auth(cli.build_parser().parse_args(["auth", "status"]))
50
+ assert "OAuth saved" in capsys.readouterr().out
51
+ assert credential_path().stat().st_mode & 0o777 == 0o600
52
+
53
+
54
+ def test_expired_token_refresh_is_serialized(monkeypatch):
55
+ credentials.save_login(SERVER, saved())
56
+ calls = []
57
+
58
+ def exchange(url, body, **kwargs):
59
+ calls.append((url, body))
60
+ time.sleep(0.1)
61
+ return fresh()
62
+
63
+ monkeypatch.setattr(credentials, "oauth_json", exchange)
64
+ with ThreadPoolExecutor(max_workers=5) as pool:
65
+ results = list(pool.map(lambda _: cli._client().workspaces()["authorization"], range(5)))
66
+ assert results == ["Bearer test-new"] * 5
67
+ assert len(calls) == 1
68
+ assert calls[0][1]["client_id"] == "test-one"
69
+ assert calls[0][1]["resource"] == SERVER + "/mcp"
70
+ assert read_credentials()["servers"][SERVER]["refresh_token"] == "test-new"
71
+
72
+
73
+ def test_ambiguous_refresh_is_not_replayed(monkeypatch):
74
+ credentials.save_login(SERVER, saved())
75
+ calls = []
76
+
77
+ def unavailable(*args, **kwargs):
78
+ calls.append(True)
79
+ raise OAuthFailure("unavailable_or_invalid_response")
80
+
81
+ monkeypatch.setattr(credentials, "oauth_json", unavailable)
82
+ for _ in range(2):
83
+ with pytest.raises(OAuthFailure):
84
+ cli._client().workspaces()
85
+ assert calls == [True]
86
+ assert read_credentials()["servers"][SERVER]["reauth_required"]
87
+
88
+
89
+ def test_server_override_does_not_reuse_project_or_other_origin_key(monkeypatch):
90
+ credentials.save_login(SERVER, saved(expires_at=time.time() + 3600))
91
+ monkeypatch.setenv("REVISO_SERVER", "https://other.test")
92
+ cfg = {"server": SERVER, "automation_key": "test-project"}
93
+ assert credentials.access_token(credentials.selected_server(cfg), cfg) == ""
94
+ monkeypatch.setenv("REVISO_AUTOMATION_KEY", "test-explicit")
95
+ assert credentials.access_token("https://other.test", cfg) == "test-explicit"
96
+
97
+
98
+
99
+
100
+ def test_invalid_token_response_preserves_reauth_required(monkeypatch):
101
+ credentials.save_login(SERVER, saved())
102
+ monkeypatch.setattr(credentials, "oauth_json", lambda *a, **k: {"access_token": "test-new"})
103
+ with pytest.raises(OAuthFailure, match="invalid_token_response"):
104
+ cli._client().workspaces()
105
+ assert read_credentials()["servers"][SERVER]["reauth_required"]
106
+
107
+
108
+ def test_world_readable_credentials_are_rejected():
109
+ credentials.save_login(SERVER, saved())
110
+ os.chmod(credential_path(), 0o644)
111
+ with pytest.raises(ValueError, match="owner-only"):
112
+ read_credentials()
113
+
114
+
115
+
116
+
117
+
118
+
119
+ def test_rate_limit_preserves_unused_refresh_for_retry(monkeypatch):
120
+ credentials.save_login(SERVER, saved())
121
+
122
+ def throttled(*args, **kwargs):
123
+ raise OAuthFailure("rate_limited")
124
+
125
+ monkeypatch.setattr(credentials, "oauth_json", throttled)
126
+ with pytest.raises(OAuthFailure, match="rate_limited"):
127
+ cli._client().workspaces()
128
+ assert not read_credentials()["servers"][SERVER].get("reauth_required")
129
+ monkeypatch.setattr(credentials, "oauth_json", lambda *a, **k: fresh())
130
+ assert cli._client().workspaces()["authorization"] == "Bearer test-new"
131
+
132
+
133
+ def test_guest_and_public_requests_do_not_refresh_an_account_login(monkeypatch):
134
+ credentials.save_login(SERVER, saved(reauth_required=True))
135
+ client = cli._client()
136
+ assert client.health()["authorization"] is None
137
+ assert client.comment("doc_fixture", "guest_fixture", "guest_secret", "Review", {})["authorization"] is None
138
+ with pytest.raises(OAuthFailure, match="login_required"):
139
+ client.workspaces()
140
+
141
+
142
+ def test_old_server_oauth_token_remains_usable_until_advertised_expiry(monkeypatch):
143
+ old = {"access_token": "test-legacy", "token_type": "Bearer", "expires_in": 31536000}
144
+ entry = {"client_id": "test-legacy", **credentials.token_fields(old, require_refresh=False)}
145
+ credentials.save_login(SERVER, entry)
146
+ assert cli._client().workspaces()["authorization"] == "Bearer test-legacy"
147
+ credentials.save_login(SERVER, {**entry, "expires_at": time.time() - 1})
148
+ with pytest.raises(OAuthFailure, match="login_required"):
149
+ cli._client().workspaces()
150
+ with pytest.raises(OAuthFailure, match="invalid_token_response"):
151
+ credentials.token_fields(old, require_refresh=True)
152
+
153
+
154
+ @pytest.mark.parametrize("server", ["", "http://127.0.0.1:5173"])
155
+ def test_key_login_validates_and_saves_selected_origin(monkeypatch, server):
156
+ requests = []
157
+
158
+ def request(req, **kwargs):
159
+ requests.append((req.full_url, req.get_header("Authorization")))
160
+ return io.BytesIO(b'{"connection_id":"key_fixture"}')
161
+
162
+ monkeypatch.setattr(http.urllib.request, "build_opener", lambda *a: SimpleNamespace(open=request))
163
+ args = cli.build_parser().parse_args(["auth", "login", "--key", "test-scoped", "--server", server])
164
+ cli.cmd_auth(args)
165
+ origin = server or "https://reviso.work"
166
+ assert requests == [(origin + "/api/agent-connection/self", "Bearer test-scoped")]
167
+ assert read_credentials()["server"] == origin
168
+ assert read_credentials()["servers"][origin]["access_token"] == "test-scoped"
169
+
170
+
171
+
172
+ def test_mapping_uses_the_same_saved_origin_as_authenticated_commands(tmp_path):
173
+ from reviso_cli.local import write_mapping
174
+
175
+ credentials.save_login(SERVER, saved(expires_at=time.time() + 3600))
176
+ source = tmp_path / 'draft.md'
177
+ source.write_text('draft')
178
+ mapping = write_mapping({'document_id': 'doc_aaaaaaaaaaaa', 'version_id': 'v1'}, source)
179
+ assert mapping['url'] == SERVER + '/documents/aaaaaaaaaaaa'
@@ -0,0 +1,112 @@
1
+ """OAuth uses real HTTP exchange and a loopback callback; only browser launch is replaced."""
2
+ import base64
3
+ import hashlib
4
+ import json
5
+ import socket
6
+ import threading
7
+ import urllib.error
8
+ import urllib.request
9
+ from concurrent.futures import ThreadPoolExecutor
10
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
11
+ from urllib.parse import parse_qs, urlencode, urlsplit
12
+
13
+ import pytest
14
+
15
+ from reviso_cli import cli
16
+ from reviso_cli.cli import oauth_login
17
+ from reviso_cli.cli.credential_file import read_credentials
18
+
19
+
20
+ class OAuthHandler(BaseHTTPRequestHandler):
21
+ def send_json(self, data, status=200):
22
+ self.send_response(status)
23
+ self.send_header('Content-Type', 'application/json')
24
+ self.end_headers()
25
+ self.wfile.write(json.dumps(data).encode())
26
+
27
+ def do_GET(self):
28
+ origin = self.server.origin
29
+ if self.path == '/.well-known/oauth-authorization-server':
30
+ self.send_json({'issuer': origin, 'code_challenge_methods_supported': ['S256'],
31
+ 'grant_types_supported': ['authorization_code', 'refresh_token'],
32
+ **{key + '_endpoint': origin + '/oauth/' + path for key, path in
33
+ [('authorization', 'authorize'), ('registration', 'register'), ('token', 'token')]}})
34
+ else:
35
+ self.send_json({'authorization': self.headers.get('Authorization')})
36
+
37
+ def do_POST(self):
38
+ body = self.rfile.read(int(self.headers.get('Content-Length', '0')))
39
+ if self.path == '/oauth/register':
40
+ data = json.loads(body)
41
+ self.server.redirect = data['redirect_uris'][0]
42
+ self.send_json({'client_id': 'test-client'})
43
+ return
44
+ data = {key: value[0] for key, value in parse_qs(body.decode()).items()}
45
+ self.server.exchanges.append(data)
46
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(data['code_verifier'].encode()).digest()).decode().rstrip('=')
47
+ if data['code'] != 'test-code' or challenge != self.server.challenge:
48
+ self.send_json({'error': 'invalid_grant'}, 400)
49
+ return
50
+ self.send_json({'access_token': 'test-access', 'refresh_token': 'test-refresh',
51
+ 'token_type': 'Bearer', 'expires_in': 3600})
52
+
53
+ def log_message(self, *_):
54
+ pass
55
+
56
+
57
+ @pytest.fixture
58
+ def oauth_server(monkeypatch, tmp_path):
59
+ lookup = socket.getaddrinfo
60
+ def loopback_only(host, *args, **kwargs):
61
+ assert host in {'127.0.0.1', 'localhost', '::1'}, 'test attempted a non-loopback request'
62
+ return lookup(host, *args, **kwargs)
63
+ monkeypatch.setattr(socket, 'getaddrinfo', loopback_only)
64
+ monkeypatch.setenv('XDG_CONFIG_HOME', str(tmp_path / 'config'))
65
+ monkeypatch.setenv('REVISO_STATE_DIR', str(tmp_path / 'state'))
66
+ monkeypatch.delenv('REVISO_SERVER', raising=False)
67
+ monkeypatch.delenv('REVISO_AUTOMATION_KEY', raising=False)
68
+ with ThreadingHTTPServer(('127.0.0.1', 0), OAuthHandler) as server:
69
+ server.origin = f'http://127.0.0.1:{server.server_port}'
70
+ server.exchanges = []
71
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
72
+ thread.start()
73
+ yield server
74
+ server.shutdown()
75
+ thread.join()
76
+
77
+
78
+ def test_browser_login_exchanges_pkce_then_authenticates_commands(oauth_server, monkeypatch, capsys):
79
+ server = oauth_server
80
+ futures = []
81
+ with ThreadPoolExecutor(max_workers=1) as pool:
82
+ def browser(url):
83
+ params = {key: value[0] for key, value in parse_qs(urlsplit(url).query).items()}
84
+ assert params['resource'] == server.origin + '/mcp'
85
+ assert params['code_challenge_method'] == 'S256'
86
+ server.challenge = params['code_challenge']
87
+ futures.append(pool.submit(callbacks, params))
88
+ return True
89
+ monkeypatch.setattr(oauth_login.webbrowser, 'open', browser)
90
+ cli.main(['auth', 'login', '--server', server.origin])
91
+ for future in futures:
92
+ future.result(timeout=3)
93
+ assert len(server.exchanges) == 1
94
+ assert server.exchanges[0]['redirect_uri'] == server.redirect
95
+ assert read_credentials()['server'] == server.origin
96
+ assert cli._client().workspaces()['authorization'] == 'Bearer test-access'
97
+ output = capsys.readouterr().out
98
+ assert 'Logged in' in output
99
+ assert 'test-access' not in output and 'test-refresh' not in output
100
+ cli.main(['auth', 'logout'])
101
+ monkeypatch.setenv('REVISO_SERVER', server.origin)
102
+ assert cli._client().workspaces()['authorization'] is None
103
+
104
+
105
+ def callbacks(params):
106
+ target = params['redirect_uri']
107
+ for query in ['code=test-code&state=wrong', f"code=a&code=b&state={params['state']}"]:
108
+ with pytest.raises(urllib.error.HTTPError) as error:
109
+ urllib.request.urlopen(target + '?' + query, timeout=2)
110
+ assert error.value.code == 400
111
+ with urllib.request.urlopen(target + '?' + urlencode({'code': 'test-code', 'state': params['state']}), timeout=2) as response:
112
+ assert response.status == 200
File without changes
File without changes