mendao-cli 1.2.1__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.
- mendao_cli/__init__.py +10 -0
- mendao_cli/account.py +234 -0
- mendao_cli/admin.py +211 -0
- mendao_cli/config.py +240 -0
- mendao_cli/device.py +191 -0
- mendao_cli/errors.py +124 -0
- mendao_cli/http.py +191 -0
- mendao_cli/library.py +248 -0
- mendao_cli/main.py +142 -0
- mendao_cli/owner.py +67 -0
- mendao_cli/parser.py +249 -0
- mendao_cli/py.typed +0 -0
- mendao_cli/result.py +21 -0
- mendao_cli/shape.py +167 -0
- mendao_cli/update.py +225 -0
- mendao_cli-1.2.1.dist-info/METADATA +134 -0
- mendao_cli-1.2.1.dist-info/RECORD +20 -0
- mendao_cli-1.2.1.dist-info/WHEEL +4 -0
- mendao_cli-1.2.1.dist-info/entry_points.txt +3 -0
- mendao_cli-1.2.1.dist-info/licenses/LICENSE +21 -0
mendao_cli/config.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""Where things are: the site's address, the key, the remembered cursors. One place per rule."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
from urllib.parse import urlsplit
|
|
13
|
+
|
|
14
|
+
from mendao_cli.errors import CliError
|
|
15
|
+
|
|
16
|
+
DEFAULT_URL = "https://mendaoai.com"
|
|
17
|
+
ENV_URL = "MENDAO_URL"
|
|
18
|
+
ENV_KEY = "MENDAO_API_KEY"
|
|
19
|
+
ENV_SECRET = "MENDAO_INTERNAL_SECRET"
|
|
20
|
+
ENV_ADMIN_KEY = "MENDAO_ADMIN_KEY"
|
|
21
|
+
ENV_CONFIG_DIR = "MENDAO_CONFIG_DIR"
|
|
22
|
+
ENV_NO_UPDATE_CHECK = "MENDAO_NO_UPDATE_CHECK"
|
|
23
|
+
KEY_PREFIX = "md_"
|
|
24
|
+
#: Placeholders count as not configured, as the tool standard asks.
|
|
25
|
+
_PLACEHOLDERS = ("YOUR_", "REPLACE_", "CHANGEME")
|
|
26
|
+
_LOOPBACK = ("127.0.0.1", "localhost", "::1")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def base_url() -> str:
|
|
30
|
+
url = (os.environ.get(ENV_URL) or DEFAULT_URL).strip().rstrip("/")
|
|
31
|
+
parts = urlsplit(url)
|
|
32
|
+
if parts.scheme not in ("http", "https") or not parts.hostname:
|
|
33
|
+
raise CliError("validation", f"{ENV_URL} 不是合法地址", suggestion=f"export {ENV_URL}={DEFAULT_URL}")
|
|
34
|
+
return url
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def is_loopback(url: str) -> bool:
|
|
38
|
+
return urlsplit(url).hostname in _LOOPBACK
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def safe_for_credentials(url: str) -> bool:
|
|
42
|
+
"""A key or secret only travels over TLS, or stays on this machine."""
|
|
43
|
+
return urlsplit(url).scheme == "https" or is_loopback(url)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def config_dir() -> Path:
|
|
47
|
+
override = os.environ.get(ENV_CONFIG_DIR)
|
|
48
|
+
if override:
|
|
49
|
+
return Path(override).expanduser()
|
|
50
|
+
if sys.platform == "win32" and os.environ.get("APPDATA"):
|
|
51
|
+
return Path(os.environ["APPDATA"]) / "mendao"
|
|
52
|
+
xdg = os.environ.get("XDG_CONFIG_HOME")
|
|
53
|
+
return (Path(xdg).expanduser() if xdg else Path.home() / ".config") / "mendao"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _usable(value: str | None) -> str | None:
|
|
57
|
+
text = (value or "").strip()
|
|
58
|
+
return text if text and not text.startswith(_PLACEHOLDERS) else None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def internal_secret() -> str | None:
|
|
62
|
+
return _usable(os.environ.get(ENV_SECRET))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def admin_key() -> str | None:
|
|
66
|
+
"""A scoped admin key, for `mendao admin`. Only ever from the environment, never a file."""
|
|
67
|
+
return _usable(os.environ.get(ENV_ADMIN_KEY))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _write_private(path: Path, value: Any) -> None:
|
|
71
|
+
"""Atomic, and owner-only from the first byte (mkstemp makes it 0600): a parallel call never reads half a file."""
|
|
72
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
73
|
+
handle, temporary = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".")
|
|
74
|
+
try:
|
|
75
|
+
with os.fdopen(handle, "w", encoding="utf-8") as stream:
|
|
76
|
+
json.dump(value, stream, ensure_ascii=False, indent=2)
|
|
77
|
+
os.replace(temporary, path)
|
|
78
|
+
except BaseException:
|
|
79
|
+
Path(temporary).unlink(missing_ok=True)
|
|
80
|
+
raise
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _read_json(path: Path) -> dict[str, Any]:
|
|
84
|
+
try:
|
|
85
|
+
value = json.loads(path.read_text("utf-8"))
|
|
86
|
+
except FileNotFoundError:
|
|
87
|
+
return {}
|
|
88
|
+
except (OSError, ValueError):
|
|
89
|
+
raise CliError("validation", f"本地文件 {path.name} 读不了", suggestion=f"删除 {path} 后重试") from None
|
|
90
|
+
return value if isinstance(value, dict) else {}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _credentials_path() -> Path:
|
|
94
|
+
return config_dir() / "credentials.json"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass(frozen=True)
|
|
98
|
+
class Key:
|
|
99
|
+
value: str
|
|
100
|
+
source: str # "env", "file" (credentials.json) or "key-file" (~/.config/mendao/key)
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def masked(self) -> str:
|
|
104
|
+
return KEY_PREFIX + "…" + self.value[-4:]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def stored_key(url: str) -> str | None:
|
|
108
|
+
"""A key is stored per site, so pointing MENDAO_URL elsewhere never sends it there."""
|
|
109
|
+
return _usable(_read_json(_credentials_path()).get("keys", {}).get(url))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def stored_origin(url: str) -> dict[str, str]:
|
|
113
|
+
"""How the stored key of this site came: `via` (key-file, stdin, prompt, env, device) and, for a device sign-in, `keyId`.
|
|
114
|
+
Empty for a key stored by a CLI older than 1.2."""
|
|
115
|
+
value = _read_json(_credentials_path()).get("origins", {}).get(url)
|
|
116
|
+
return {k: str(v) for k, v in value.items()} if isinstance(value, dict) else {}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def key_location(key: Key) -> str:
|
|
120
|
+
"""Where `whoami` says the key lives: a path, or the variable it came from."""
|
|
121
|
+
if key.source == "env":
|
|
122
|
+
return "$" + ENV_KEY
|
|
123
|
+
return str(key_file_path() if key.source == "key-file" else _credentials_path())
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def decode_key_bytes(raw: bytes) -> str:
|
|
127
|
+
"""Text as Windows tools write it: UTF-8 with or without a BOM, or UTF-16 with a BOM (PowerShell 5 `>`), CRLF or LF. Raises ValueError for anything else."""
|
|
128
|
+
if raw.startswith((b"\xff\xfe", b"\xfe\xff")):
|
|
129
|
+
return raw.decode("utf-16").strip()
|
|
130
|
+
return raw.decode("utf-8-sig").strip()
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def key_file_path() -> Path:
|
|
134
|
+
"""Where the guide tells readers to keep the key, the same on every system: `~/.config/mendao/key`, whatever config_dir() says."""
|
|
135
|
+
return Path.home() / ".config" / "mendao" / "key"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _key_from_key_file() -> str | None:
|
|
139
|
+
try:
|
|
140
|
+
return _usable(decode_key_bytes(key_file_path().read_bytes()))
|
|
141
|
+
except (OSError, ValueError, RuntimeError): # Missing, unreadable, empty or in no accepted encoding: not configured, and no error for a fallback.
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def current_key(url: str) -> Key | None:
|
|
146
|
+
env = _usable(os.environ.get(ENV_KEY))
|
|
147
|
+
if env:
|
|
148
|
+
return Key(env, "env")
|
|
149
|
+
stored = stored_key(url)
|
|
150
|
+
if stored:
|
|
151
|
+
return Key(stored, "file")
|
|
152
|
+
# The key file belongs to the default site only: a key is per site, so another MENDAO_URL never receives it.
|
|
153
|
+
if url == DEFAULT_URL and safe_for_credentials(url):
|
|
154
|
+
fallback = _key_from_key_file()
|
|
155
|
+
if fallback:
|
|
156
|
+
return Key(fallback, "key-file")
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def save_key(url: str, key: str, origin: dict[str, str] | None = None) -> Path:
|
|
161
|
+
"""Every way in ends here, so a key from the browser and one from a file are stored the same way: this file, 0600, atomic."""
|
|
162
|
+
path = _credentials_path()
|
|
163
|
+
data = _read_json(path)
|
|
164
|
+
data.setdefault("keys", {})[url] = key
|
|
165
|
+
origins = data.setdefault("origins", {})
|
|
166
|
+
if origin:
|
|
167
|
+
origins[url] = origin
|
|
168
|
+
else:
|
|
169
|
+
origins.pop(url, None)
|
|
170
|
+
_write_private(path, data)
|
|
171
|
+
return path
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def forget_key(url: str) -> bool:
|
|
175
|
+
path = _credentials_path()
|
|
176
|
+
data = _read_json(path)
|
|
177
|
+
keys = data.get("keys", {})
|
|
178
|
+
if url not in keys:
|
|
179
|
+
return False
|
|
180
|
+
del keys[url]
|
|
181
|
+
data.get("origins", {}).pop(url, None)
|
|
182
|
+
_write_private(path, data)
|
|
183
|
+
return True
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _device_path() -> Path:
|
|
187
|
+
return config_dir() / "device.json"
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def pending_device(url: str) -> dict[str, Any] | None:
|
|
191
|
+
"""The device code a `mendao login` started for this site and `mendao login --wait` collects. It can fetch a key once approved, so it is kept like one."""
|
|
192
|
+
value = _read_json(_device_path()).get("pending", {}).get(url)
|
|
193
|
+
return value if isinstance(value, dict) else None
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def save_pending_device(url: str, pending: dict[str, Any]) -> None:
|
|
197
|
+
path = _device_path()
|
|
198
|
+
data = _read_json(path)
|
|
199
|
+
data.setdefault("pending", {})[url] = pending
|
|
200
|
+
_write_private(path, data)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def clear_pending_device(url: str, device_code: str) -> None:
|
|
204
|
+
"""Only the code this run worked on: a newer one another run stored meanwhile stays."""
|
|
205
|
+
path = _device_path()
|
|
206
|
+
data = _read_json(path)
|
|
207
|
+
pending = data.get("pending", {})
|
|
208
|
+
current = pending.get(url)
|
|
209
|
+
if isinstance(current, dict) and current.get("device_code") == device_code:
|
|
210
|
+
del pending[url]
|
|
211
|
+
_write_private(path, data)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def update_check_disabled() -> bool:
|
|
215
|
+
return (os.environ.get(ENV_NO_UPDATE_CHECK) or "").strip().lower() not in ("", "0", "false", "no")
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _cursor_path(url: str, consumer: str) -> Path:
|
|
219
|
+
name = hashlib.sha256(f"{url}\n{consumer}".encode()).hexdigest()[:24]
|
|
220
|
+
return config_dir() / "changes" / f"{name}.json"
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def stored_cursor(url: str, consumer: str) -> int:
|
|
224
|
+
value = _read_json(_cursor_path(url, consumer)).get("cursor", 0)
|
|
225
|
+
return value if isinstance(value, int) and value >= 0 else 0
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def save_cursor(url: str, consumer: str, cursor: int) -> None:
|
|
229
|
+
_write_private(_cursor_path(url, consumer), {"url": url, "consumer": consumer, "cursor": cursor})
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def require_writable_state() -> None:
|
|
233
|
+
"""Asked before fetching, so a batch is never delivered and then forgotten."""
|
|
234
|
+
directory = config_dir() / "changes"
|
|
235
|
+
try:
|
|
236
|
+
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
237
|
+
with tempfile.TemporaryFile(dir=directory):
|
|
238
|
+
pass
|
|
239
|
+
except OSError:
|
|
240
|
+
raise CliError("dependency", "本地状态目录不可写,记不住同步位置", suggestion=f"export {ENV_CONFIG_DIR}=<可写目录>") from None
|
mendao_cli/device.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Signing in from the command line: the device grant (RFC 8628, design 3.5). What comes back is a personal key, named after this
|
|
2
|
+
machine in the member centre and stored the way any other key is. The device code can fetch that key once the reader approves,
|
|
3
|
+
so it is kept like a key: in a 0600 file, never in output."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
import socket
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
import webbrowser
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from typing import Any
|
|
13
|
+
from urllib.parse import urlsplit
|
|
14
|
+
|
|
15
|
+
from mendao_cli import config
|
|
16
|
+
from mendao_cli.errors import CliError
|
|
17
|
+
from mendao_cli.http import DEFAULT_TIMEOUT, Site, rate_limited
|
|
18
|
+
|
|
19
|
+
CLIENT_ID = "mendao-cli"
|
|
20
|
+
GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code"
|
|
21
|
+
DEVICE_PATH = "/api/v1/oauth/device"
|
|
22
|
+
TOKEN_PATH = "/api/v1/oauth/token"
|
|
23
|
+
REVOKE_PATH = "/api/v1/oauth/revoke"
|
|
24
|
+
DEFAULT_INTERVAL = 5
|
|
25
|
+
#: RFC 8628 section 3.5: every slow_down adds five seconds, for that poll and every later one.
|
|
26
|
+
SLOW_DOWN_SECONDS = 5
|
|
27
|
+
#: After a failed poll (no connection, a 5xx) the wait doubles, up to this.
|
|
28
|
+
MAX_BACKOFF_SECONDS = 60
|
|
29
|
+
MAX_DEVICE_NAME = 60
|
|
30
|
+
#: A pending code with less than this left is not handed out again: the reader could not finish in time.
|
|
31
|
+
MIN_REUSE_SECONDS = 60
|
|
32
|
+
|
|
33
|
+
#: Indirections the tests replace: a fake clock, and no browser.
|
|
34
|
+
_now: Callable[[], float] = time.time
|
|
35
|
+
_sleep: Callable[[float], None] = time.sleep
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _open_browser(url: str) -> bool:
|
|
39
|
+
"""Only where a browser can appear in front of the reader: not over SSH, and on Linux only with a display
|
|
40
|
+
(without one, webbrowser falls back to a text browser that takes over the terminal)."""
|
|
41
|
+
if os.environ.get("SSH_CONNECTION") or os.environ.get("SSH_TTY"):
|
|
42
|
+
return False
|
|
43
|
+
if sys.platform.startswith("linux") and not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):
|
|
44
|
+
return False
|
|
45
|
+
try:
|
|
46
|
+
return webbrowser.open(url, new=2)
|
|
47
|
+
except webbrowser.Error:
|
|
48
|
+
return False
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def device_name() -> str:
|
|
52
|
+
"""Shown on the confirmation page and in the key's name: the host's short name, nothing else about the reader."""
|
|
53
|
+
name = socket.gethostname().split(".")[0].strip()
|
|
54
|
+
return (name or "unknown")[:MAX_DEVICE_NAME]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _json(response: Any) -> dict[str, Any]:
|
|
58
|
+
try:
|
|
59
|
+
value = response.json()
|
|
60
|
+
except ValueError:
|
|
61
|
+
return {}
|
|
62
|
+
return value if isinstance(value, dict) else {}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _web_address(value: Any) -> str:
|
|
66
|
+
"""The page the reader opens. Anything but https (or this machine) is refused: it is about to be handed to a browser."""
|
|
67
|
+
text = str(value or "")
|
|
68
|
+
parts = urlsplit(text)
|
|
69
|
+
if parts.hostname and (parts.scheme == "https" or (parts.scheme == "http" and config.is_loopback(text))):
|
|
70
|
+
return text
|
|
71
|
+
raise CliError("api", "门道给的确认地址不是网页地址", code=502, suggestion="稍后重试;一直这样请改用 mendao login --key-file ~/.config/mendao/key")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def seconds_left(pending: dict[str, Any]) -> int:
|
|
75
|
+
return max(0, round(float(pending["expires_at"]) - _now()))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def start(site: Site) -> dict[str, Any]:
|
|
79
|
+
response = site.send("POST", DEVICE_PATH, form={"client_id": CLIENT_ID, "device_name": device_name()})
|
|
80
|
+
status = response.status_code
|
|
81
|
+
if status in (404, 405):
|
|
82
|
+
raise CliError("dependency", "这个站点还不支持在浏览器里确认登录", code=status, error_code="mendao.device-unsupported")
|
|
83
|
+
if status == 429:
|
|
84
|
+
raise rate_limited(response)
|
|
85
|
+
body = _json(response)
|
|
86
|
+
expires = body.get("expires_in")
|
|
87
|
+
if status != 200 or not isinstance(body.get("device_code"), str) or not isinstance(body.get("user_code"), str) or not isinstance(expires, int) or expires <= 0:
|
|
88
|
+
raise CliError("api", f"门道没能开始登录({status})", code=status if status >= 400 else 502, suggestion="稍后重试;一直这样请改用 mendao login --key-file ~/.config/mendao/key")
|
|
89
|
+
now = _now()
|
|
90
|
+
interval = body.get("interval")
|
|
91
|
+
pending: dict[str, Any] = {
|
|
92
|
+
"device_code": body["device_code"],
|
|
93
|
+
"user_code": body["user_code"],
|
|
94
|
+
"verification_uri": _web_address(body.get("verification_uri")),
|
|
95
|
+
"verification_uri_complete": _web_address(body.get("verification_uri_complete") or body.get("verification_uri")),
|
|
96
|
+
"interval": interval if isinstance(interval, int) and interval > 0 else DEFAULT_INTERVAL,
|
|
97
|
+
"expires_at": now + expires,
|
|
98
|
+
"created_at": now,
|
|
99
|
+
"polled_at": None,
|
|
100
|
+
}
|
|
101
|
+
config.save_pending_device(site.url, pending)
|
|
102
|
+
return pending
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def pending_or_start(site: Site) -> dict[str, Any]:
|
|
106
|
+
"""A second `mendao login` while one waits gets the same code: the reader may already have the page open."""
|
|
107
|
+
pending = config.pending_device(site.url)
|
|
108
|
+
if pending is not None and seconds_left(pending) >= MIN_REUSE_SECONDS:
|
|
109
|
+
return pending
|
|
110
|
+
return start(site)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def public_view(pending: dict[str, Any]) -> dict[str, Any]:
|
|
114
|
+
"""What may be shown: everything but the device code."""
|
|
115
|
+
return {"verification_uri": pending["verification_uri"], "verification_uri_complete": pending["verification_uri_complete"],
|
|
116
|
+
"user_code": pending["user_code"], "expires_in": seconds_left(pending)}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def wait(site: Site, pending: dict[str, Any], budget: float) -> dict[str, Any]:
|
|
120
|
+
"""Polls until the reader approves, denies, the code expires, or `budget` seconds pass. Returns the token endpoint's answer."""
|
|
121
|
+
code = str(pending["device_code"])
|
|
122
|
+
expires_at = float(pending["expires_at"])
|
|
123
|
+
deadline = min(_now() + budget, expires_at)
|
|
124
|
+
interval = int(pending.get("interval") or DEFAULT_INTERVAL)
|
|
125
|
+
failures = 0
|
|
126
|
+
while True:
|
|
127
|
+
if _now() >= expires_at:
|
|
128
|
+
config.clear_pending_device(site.url, code)
|
|
129
|
+
raise CliError("auth", "这次登录的代码过期了", error_code="mendao.device-expired", suggestion="重新运行 mendao login,拿一个新代码")
|
|
130
|
+
step = min(MAX_BACKOFF_SECONDS, interval << failures)
|
|
131
|
+
due = float(pending.get("polled_at") or pending["created_at"]) + step
|
|
132
|
+
if due >= deadline:
|
|
133
|
+
break
|
|
134
|
+
if due > _now():
|
|
135
|
+
_sleep(due - _now())
|
|
136
|
+
try:
|
|
137
|
+
response = site.send("POST", TOKEN_PATH, form={"grant_type": GRANT_TYPE, "device_code": code, "client_id": CLIENT_ID},
|
|
138
|
+
timeout=min(DEFAULT_TIMEOUT, max(1.0, deadline - _now())))
|
|
139
|
+
except CliError as error:
|
|
140
|
+
if error.error_type not in ("network", "timeout"):
|
|
141
|
+
raise
|
|
142
|
+
failures += 1
|
|
143
|
+
pending["polled_at"] = _now()
|
|
144
|
+
continue
|
|
145
|
+
pending["polled_at"] = _now()
|
|
146
|
+
status, answer = response.status_code, _json(response)
|
|
147
|
+
if status == 200:
|
|
148
|
+
config.clear_pending_device(site.url, code)
|
|
149
|
+
return answer
|
|
150
|
+
error_code = str(answer.get("error") or "")
|
|
151
|
+
if status >= 500:
|
|
152
|
+
failures += 1
|
|
153
|
+
elif error_code == "authorization_pending":
|
|
154
|
+
failures = 0
|
|
155
|
+
elif error_code == "slow_down" or status == 429:
|
|
156
|
+
failures = 0
|
|
157
|
+
interval += SLOW_DOWN_SECONDS
|
|
158
|
+
pending["interval"] = interval
|
|
159
|
+
elif error_code == "access_denied":
|
|
160
|
+
config.clear_pending_device(site.url, code)
|
|
161
|
+
raise CliError("auth", "读者在浏览器里拒绝了这次登录", error_code="mendao.device-denied", suggestion="要登录就重新运行 mendao login,请读者在浏览器里确认")
|
|
162
|
+
elif error_code == "expired_token":
|
|
163
|
+
config.clear_pending_device(site.url, code)
|
|
164
|
+
raise CliError("auth", "这次登录的代码过期了", error_code="mendao.device-expired", suggestion="重新运行 mendao login,拿一个新代码")
|
|
165
|
+
else:
|
|
166
|
+
# invalid_grant and the rest: the server does not know this code (already collected by another run, or swept).
|
|
167
|
+
config.clear_pending_device(site.url, code)
|
|
168
|
+
raise CliError("api", f"门道不认这次登录({error_code or status})", code=status,
|
|
169
|
+
suggestion="mendao whoami 看是否已经登录(另一个 mendao login --wait 可能已经取走了密钥);没有就重新运行 mendao login")
|
|
170
|
+
config.save_pending_device(site.url, pending)
|
|
171
|
+
if due >= expires_at:
|
|
172
|
+
config.clear_pending_device(site.url, code)
|
|
173
|
+
raise CliError("auth", "这次登录的代码过期了", error_code="mendao.device-expired", suggestion="重新运行 mendao login,拿一个新代码")
|
|
174
|
+
config.save_pending_device(site.url, pending)
|
|
175
|
+
if failures:
|
|
176
|
+
raise CliError("network", "等确认时连不上门道", error_code="mendao.offline", suggestion="网络恢复后运行 mendao login --wait", details=public_view(pending))
|
|
177
|
+
raise CliError("timeout", "等到 --timeout,读者还没在浏览器里确认登录", error_code="mendao.device-timeout", side_effects="none",
|
|
178
|
+
suggestion="mendao login --wait", details=public_view(pending))
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def revoke(site: Site, key: str) -> bool:
|
|
182
|
+
"""Asks the server to revoke a key this CLI received (RFC 7009, design 3.2 "Revocation"): presenting the key revokes it.
|
|
183
|
+
The key goes in the form body, to this site only, and only over https (or this machine). True only on a 200; an older
|
|
184
|
+
server (404, 405), no connection or a timeout is False, and the caller says the key is still valid."""
|
|
185
|
+
if not config.safe_for_credentials(site.url):
|
|
186
|
+
return False
|
|
187
|
+
try:
|
|
188
|
+
response = site.send("POST", REVOKE_PATH, form={"token": key, "token_type_hint": "access_token", "client_id": CLIENT_ID})
|
|
189
|
+
except CliError:
|
|
190
|
+
return False
|
|
191
|
+
return response.status_code == 200
|
mendao_cli/errors.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""The error contract: one exception, its envelope, its exit code, and the catalogue of known situations."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from collections.abc import Iterable
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
MAX_EDITS = 2
|
|
8
|
+
#: error_type: (default HTTP-like code, retryable, side effects, exit code).
|
|
9
|
+
ERROR_TYPES: dict[str, tuple[int, bool, str, int]] = {
|
|
10
|
+
"validation": (400, False, "none", 2),
|
|
11
|
+
"auth": (401, False, "none", 4),
|
|
12
|
+
"security": (403, False, "none", 4),
|
|
13
|
+
"not_found": (404, False, "none", 3),
|
|
14
|
+
"conflict": (409, False, "none", 5),
|
|
15
|
+
"rate_limit": (429, True, "none", 1),
|
|
16
|
+
"timeout": (504, True, "unknown", 1),
|
|
17
|
+
"api": (502, True, "unknown", 1),
|
|
18
|
+
"network": (503, True, "unknown", 1),
|
|
19
|
+
"dependency": (424, False, "none", 6),
|
|
20
|
+
"cancelled": (499, False, "unknown", 1),
|
|
21
|
+
"internal": (500, False, "unknown", 1),
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
#: Stable ids of what can be explained. `commands --explain <id>` reads this; ids are never renamed.
|
|
25
|
+
GUIDANCE: dict[str, dict[str, str]] = {
|
|
26
|
+
"mendao.free-limit": {"kind": "notice", "text": "没有密钥时,只能读公开内容,即每个问题排名前 20 的做法。", "fix": "运行 mendao login,在浏览器里确认登录;或到 {url}/me 创建 Agent 密钥,再运行 mendao login --key-file ~/.config/mendao/key"},
|
|
27
|
+
"mendao.needs-key": {"kind": "error", "text": "这项内容要 Agent 密钥。", "fix": "运行 mendao login,在浏览器里确认登录;或到 {url}/me 创建 Agent 密钥,再运行 mendao login --key-file ~/.config/mendao/key"},
|
|
28
|
+
"mendao.needs-membership": {"kind": "error", "text": "密钥有效,但这个账号的会员没开通或已到期。", "fix": "到 {url}/membership 开通或续费;不开通会员也能读每个问题排名前 60 的做法"},
|
|
29
|
+
"mendao.key-rejected": {"kind": "error", "text": "服务器不认这把密钥,可能已撤销。", "fix": "重新运行 mendao login;或到 {url}/me 重新创建,再运行 mendao login --key-file ~/.config/mendao/key"},
|
|
30
|
+
"mendao.offline": {"kind": "error", "text": "连不上门道。", "fix": "检查网络后重试;地址可用环境变量 MENDAO_URL 改"},
|
|
31
|
+
"mendao.rate-limited": {"kind": "error", "text": "调用太频繁,已被限流。", "fix": "有 retry_after 就等这么多秒再试,没有就是服务器没说,过一会儿再试;缩小范围或用 mendao changes 增量同步"},
|
|
32
|
+
"mendao.daily-limit": {"kind": "error", "text": "这把密钥今天的调用次数用完了,额度每天 UTC 0 点恢复。", "fix": "等到 retry_after 秒之后(UTC 0 点)再试,在那之前重试不会成功;mendao whoami 看今天的用量"},
|
|
33
|
+
"mendao.update": {"kind": "notice", "text": "有新版的 mendao-cli。", "fix": "运行 mendao update 原地升级;不想看到这条提示:export MENDAO_NO_UPDATE_CHECK=1"},
|
|
34
|
+
"mendao.insecure-url": {"kind": "error", "text": "地址不是 https,密钥不会发出去。", "fix": "把 MENDAO_URL 改成 https 地址"},
|
|
35
|
+
"mendao.device-pending": {"kind": "notice", "text": "等读者在浏览器里确认登录:打开 {uri},核对代码 {code}。", "fix": "把地址和代码告诉读者;他确认后运行 mendao login --wait"},
|
|
36
|
+
"mendao.device-timeout": {"kind": "error", "text": "等到 --timeout,读者还没在浏览器里确认登录。", "fix": "把 details 里的地址和代码再告诉读者一次,然后运行 mendao login --wait"},
|
|
37
|
+
"mendao.device-denied": {"kind": "error", "text": "读者在浏览器里拒绝了这次登录。", "fix": "要登录就重新运行 mendao login,请读者在浏览器里确认"},
|
|
38
|
+
"mendao.device-expired": {"kind": "error", "text": "这次登录的代码过期了,读者没在有效期内确认。", "fix": "重新运行 mendao login,拿一个新代码"},
|
|
39
|
+
"mendao.device-unsupported": {"kind": "error", "text": "这个站点还不支持在浏览器里确认登录。", "fix": "到 {url}/me 创建 Agent 密钥,存进文件,再运行 mendao login --key-file ~/.config/mendao/key"},
|
|
40
|
+
"mendao.signed-in": {"kind": "notice", "text": "这台机器已经登录门道,没有再申请新密钥。", "fix": "mendao whoami 看详情;要换一把密钥,先 mendao logout,再 mendao login"},
|
|
41
|
+
"mendao.no-pending-login": {"kind": "error", "text": "没有等待确认的登录。", "fix": "先运行 mendao login;已经登录的话,mendao whoami 看现在用哪把密钥"},
|
|
42
|
+
"mendao.key-still-valid": {"kind": "notice", "text": "密钥 {key_id} 只从本机删除了:服务器这次没能作废它,它仍然有效,直到在会员中心撤销。", "fix": "到 {url}/me 撤销这把密钥(名字以「命令行」开头)"},
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class CliError(Exception):
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
error_type: str,
|
|
50
|
+
message: str,
|
|
51
|
+
*,
|
|
52
|
+
suggestion: str | None = None,
|
|
53
|
+
code: int | None = None,
|
|
54
|
+
side_effects: str | None = None,
|
|
55
|
+
retry_after: int | None = None,
|
|
56
|
+
did_you_mean: list[str] | None = None,
|
|
57
|
+
error_code: str | None = None,
|
|
58
|
+
details: Any = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
super().__init__(message)
|
|
61
|
+
self.error_type = error_type
|
|
62
|
+
self.message = message
|
|
63
|
+
self.suggestion = suggestion
|
|
64
|
+
self.code = code
|
|
65
|
+
self.side_effects = side_effects
|
|
66
|
+
self.retry_after = retry_after
|
|
67
|
+
self.did_you_mean = did_you_mean
|
|
68
|
+
self.error_code = error_code
|
|
69
|
+
#: The server's structured account of a refusal, such as every problem a check found.
|
|
70
|
+
self.details = details
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def exit_code(self) -> int:
|
|
74
|
+
return ERROR_TYPES[self.error_type][3]
|
|
75
|
+
|
|
76
|
+
def envelope(self, *, argv: list[str], url: str) -> dict[str, Any]:
|
|
77
|
+
code, retryable, side_effects, _ = ERROR_TYPES[self.error_type]
|
|
78
|
+
out: dict[str, Any] = {
|
|
79
|
+
"code": self.code or code,
|
|
80
|
+
"error": self.message,
|
|
81
|
+
"error_type": self.error_type,
|
|
82
|
+
"retryable": retryable,
|
|
83
|
+
"side_effects": self.side_effects or side_effects,
|
|
84
|
+
"input": {"argv": argv},
|
|
85
|
+
"documentation": [{"kind": "guide", "path": f"{url}/connect"}],
|
|
86
|
+
"discovery": {"command": "mendao commands <command-path>", "full": "mendao commands --full"},
|
|
87
|
+
}
|
|
88
|
+
suggestion = self.suggestion
|
|
89
|
+
if self.error_code:
|
|
90
|
+
entry = GUIDANCE[self.error_code]
|
|
91
|
+
fix = entry["fix"].format(url=url)
|
|
92
|
+
out["error_code"] = self.error_code
|
|
93
|
+
out["guidance"] = {"text": entry["text"], "fix": fix}
|
|
94
|
+
suggestion = suggestion or fix
|
|
95
|
+
out["suggestion"] = suggestion or "mendao commands"
|
|
96
|
+
if self.retry_after is not None:
|
|
97
|
+
out["retry_after"] = self.retry_after
|
|
98
|
+
if self.did_you_mean:
|
|
99
|
+
out["did_you_mean"] = self.did_you_mean
|
|
100
|
+
if self.details is not None:
|
|
101
|
+
out["details"] = self.details
|
|
102
|
+
return out
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _distance(a: str, b: str) -> int:
|
|
106
|
+
previous = list(range(len(b) + 1))
|
|
107
|
+
for i, left in enumerate(a, 1):
|
|
108
|
+
current = [i]
|
|
109
|
+
for j, right in enumerate(b, 1):
|
|
110
|
+
current.append(min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (left != right)))
|
|
111
|
+
previous = current
|
|
112
|
+
return previous[-1]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def close_matches(word: str, options: Iterable[str]) -> list[str]:
|
|
116
|
+
"""At most three, within two edits, nearest first. `options` come from our own definitions, never from input."""
|
|
117
|
+
scored = sorted((_distance(word, option), option) for option in set(options))
|
|
118
|
+
return [option for distance, option in scored if distance <= MAX_EDITS][:3]
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def notice(notice_id: str, url: str, **values: Any) -> dict[str, str]:
|
|
122
|
+
"""A remark that is not a failure, rendered from the catalogue only: upstream text never reaches it."""
|
|
123
|
+
entry = GUIDANCE[notice_id]
|
|
124
|
+
return {"id": notice_id, "text": entry["text"].format(**values) if values else entry["text"], "fix": entry["fix"].format(url=url)}
|