maco-cli 0.4.5__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.
@@ -0,0 +1,436 @@
1
+ """Select a route and open a mail socket without changing the TLS identity."""
2
+ import base64
3
+ import errno
4
+ import hashlib
5
+ import ipaddress
6
+ import json
7
+ import logging
8
+ import os
9
+ import re
10
+ import socket
11
+ import ssl
12
+ import struct
13
+ import time
14
+ from contextlib import contextmanager, suppress
15
+ from contextvars import ContextVar
16
+ from dataclasses import dataclass, field
17
+ from typing import Optional, Tuple
18
+ from urllib.parse import unquote_to_bytes, urlsplit
19
+ from urllib.request import getproxies_environment, proxy_bypass_environment
20
+
21
+ from .accounts import _atomic_write, _directory, _host, _locked, _read_private, _write_private
22
+ from .errors import MacoError, MailError
23
+
24
+
25
+ LOG = logging.getLogger(__name__)
26
+ PROXY_ENV = "MACO_MAIL_PROXY"
27
+ _FAKE_DNS = ipaddress.IPv4Network("198.18.0.0/15")
28
+ _ROUTE_TTL = 86400
29
+ _NETWORK_FAILURES = frozenset({
30
+ "timeout", "connection_refused", "connection_reset", "connection_closed",
31
+ "connection_failed", "host_unreachable", "network_unreachable", "unexpected_eof",
32
+ })
33
+ _NO_PROXY_HINT = ("This network may block mail ports. Set MACO_MAIL_PROXY or save an HTTP CONNECT "
34
+ "or SOCKS5 proxy with maco proxy set.")
35
+ _route_report = ContextVar("mail_route_report", default=None)
36
+
37
+
38
+ @contextmanager
39
+ def capture_route():
40
+ """Collect a check's route. If any connection uses a proxy, report it."""
41
+ report = {}
42
+ token = _route_report.set(report)
43
+ try:
44
+ yield report
45
+ finally:
46
+ _route_report.reset(token)
47
+
48
+
49
+ def _authority(host, port):
50
+ return f"[{host}]:{port}" if ":" in host else f"{host}:{port}"
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class _Proxy:
55
+ scheme: str
56
+ host: str
57
+ port: int
58
+ auth: Optional[Tuple[bytes, bytes]] = field(default=None, repr=False)
59
+
60
+ @property
61
+ def address(self):
62
+ return f"{self.scheme}://{_authority(self.host, self.port)}"
63
+
64
+
65
+ def _proxy_config(protocol, name, setting):
66
+ try:
67
+ if len(setting) > 4096 or any(c.isspace() or not c.isprintable() or c in "\\?#" for c in setting):
68
+ raise ValueError()
69
+ url = urlsplit(setting)
70
+ if url.scheme not in ("http", "socks5", "socks5h") or not url.hostname or url.path not in ("", "/"):
71
+ raise ValueError()
72
+ scheme = url.scheme
73
+ host = _host(url.hostname)
74
+ port = url.port
75
+ if port == 0:
76
+ raise ValueError()
77
+ auth = None
78
+ if url.username is not None:
79
+ user = unquote_to_bytes(url.username)
80
+ password = unquote_to_bytes(url.password or "")
81
+ if (not 1 <= len(user) <= 255 or len(password) > 255
82
+ or (scheme == "http" and b":" in user)
83
+ or (scheme != "http" and not password)
84
+ or any(byte < 32 or byte == 127 for byte in user + password)):
85
+ raise ValueError()
86
+ auth = (user, password)
87
+ return _Proxy(scheme, host, port or (80 if scheme == "http" else 1080), auth)
88
+ except (ValueError, UnicodeError, MacoError):
89
+ raise MailError(f"Set {name} to an HTTP CONNECT or SOCKS5 proxy URL.",
90
+ protocol, "proxy", reason="invalid_proxy_url") from None
91
+
92
+
93
+ def _saved_setting():
94
+ try:
95
+ return _read_private(_directory() / "mail-proxy").decode("utf-8")
96
+ except FileNotFoundError:
97
+ return None
98
+ except UnicodeError:
99
+ raise MacoError("Invalid saved proxy. Use maco proxy set or maco proxy clear.") from None
100
+
101
+
102
+ def _configured_proxy(protocol, name, setting):
103
+ return None if setting.strip().lower() == "direct" else _proxy_config(protocol, name, setting)
104
+
105
+
106
+ def _ambient_proxy(protocol, proxies):
107
+ for name in ("all", "https"):
108
+ setting = proxies.get(name)
109
+ if setting:
110
+ with suppress(MailError):
111
+ return setting, _proxy_config(protocol, name.upper() + "_PROXY", setting)
112
+ return None, None
113
+
114
+
115
+ def save_proxy(setting):
116
+ explicit = setting is not None
117
+ if not explicit:
118
+ env = getproxies_environment()
119
+ setting = env.get("maco_mail") or _ambient_proxy("mail", env)[0]
120
+ if not setting:
121
+ raise MacoError("Provide a proxy URL or set MACO_MAIL_PROXY in this terminal first.")
122
+ proxy = _configured_proxy("mail", "the proxy", setting)
123
+ if explicit and proxy and proxy.auth:
124
+ raise MacoError("Set MACO_MAIL_PROXY in the environment and run maco proxy set without a URL for an authenticated proxy.")
125
+ directory = _directory()
126
+ with _locked(directory / "mail-proxy.lock"):
127
+ _write_private(directory / "mail-proxy", setting.encode("utf-8"))
128
+ return {"mode": "saved", **_route_fields(proxy)}
129
+
130
+
131
+ def show_proxy():
132
+ setting = _saved_setting()
133
+ if setting is None:
134
+ return {"mode": "automatic"}
135
+ return {"mode": "saved", **_route_fields(_configured_proxy("mail", "the saved proxy", setting))}
136
+
137
+
138
+ def clear_proxy():
139
+ directory = _directory()
140
+ with _locked(directory / "mail-proxy.lock"):
141
+ (directory / "mail-proxy").unlink(missing_ok=True)
142
+ return {"mode": "automatic"}
143
+
144
+
145
+ def _select_proxy(protocol, host, port):
146
+ # Use explicit local settings and the process environment for mail sockets.
147
+ proxies = getproxies_environment()
148
+ setting = proxies.get("maco_mail")
149
+ if (setting and setting.strip().lower() == "direct"
150
+ or proxy_bypass_environment(_authority(host, port), proxies)
151
+ or (":" in host and proxy_bypass_environment(host, proxies))):
152
+ return None, True
153
+ if setting:
154
+ return _proxy_config(protocol, PROXY_ENV, setting), True
155
+ saved = _saved_setting()
156
+ if saved is not None:
157
+ return _configured_proxy(protocol, "the saved proxy", saved), True
158
+ _, ambient = _ambient_proxy(protocol, proxies)
159
+ return ambient, False
160
+
161
+
162
+ def _resolves_to_fake_ip(host, port):
163
+ try:
164
+ addresses = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
165
+ except socket.gaierror:
166
+ return False
167
+ return any(family == socket.AF_INET and ipaddress.IPv4Address(address[0]) in _FAKE_DNS
168
+ for family, _, _, _, address in addresses)
169
+
170
+
171
+ def _route_fields(proxy):
172
+ return {"via": "proxy", "proxy": proxy.address} if proxy else {"via": "direct"}
173
+
174
+
175
+ def _cache_path(host, port):
176
+ key = hashlib.sha256(_authority(host.lower(), port).encode("utf-8")).hexdigest()
177
+ with suppress(OSError, MacoError):
178
+ return _directory() / "mail-routes" / (key + ".json")
179
+ return None
180
+
181
+
182
+ def _cached_route(path, proxy):
183
+ if path is not None:
184
+ with suppress(OSError, ValueError):
185
+ record = json.loads(path.read_bytes())
186
+ if isinstance(record, dict) and type(record.get("expires_at")) is int and record["expires_at"] > time.time():
187
+ if record.get("via") == "direct":
188
+ return "direct"
189
+ if record.get("via") == "proxy" and record.get("proxy") == proxy.address:
190
+ return "proxy"
191
+ return None
192
+
193
+
194
+ def _save_route(path, fields):
195
+ if path is not None:
196
+ with suppress(OSError):
197
+ path.parent.mkdir(mode=0o700, exist_ok=True)
198
+ record = {**fields, "expires_at": int(time.time()) + _ROUTE_TTL}
199
+ _atomic_write(path, json.dumps(record).encode("utf-8"))
200
+
201
+
202
+ def _retryable(error, proxy):
203
+ stage = error.details.get("stage")
204
+ reason = error.details.get("reason")
205
+ if stage in ("tcp", "tls"):
206
+ return reason in _NETWORK_FAILURES
207
+ if proxy and stage == "proxy":
208
+ return (reason in _NETWORK_FAILURES or reason in ("server_failure", "ttl_expired")
209
+ or error.details.get("http_status") in (500, 502, 503, 504))
210
+ return bool(proxy) and stage == "dns"
211
+
212
+
213
+ def _attempt_fields(error):
214
+ return {key: error.details[key] for key in ("via", "proxy", "stage", "reason") if key in error.details}
215
+
216
+
217
+ def socket_reason(exc):
218
+ if isinstance(exc, TimeoutError):
219
+ return "timeout"
220
+ return {
221
+ errno.ECONNREFUSED: "connection_refused",
222
+ errno.ECONNRESET: "connection_reset",
223
+ errno.EHOSTUNREACH: "host_unreachable",
224
+ errno.ENETUNREACH: "network_unreachable",
225
+ errno.ETIMEDOUT: "timeout",
226
+ errno.EPIPE: "connection_closed",
227
+ }.get(getattr(exc, "errno", None), "connection_failed")
228
+
229
+
230
+ def tls_error(protocol, exc):
231
+ details = {}
232
+ if isinstance(exc, ssl.SSLCertVerificationError):
233
+ reason = "certificate_verification_failed"
234
+ code = getattr(exc, "verify_code", None)
235
+ if isinstance(code, int):
236
+ details["verify_code"] = code
237
+ elif isinstance(exc, ssl.SSLEOFError) or (
238
+ isinstance(exc, ssl.SSLError) and getattr(exc, "reason", None) == "UNEXPECTED_EOF_WHILE_READING"):
239
+ reason = "unexpected_eof"
240
+ elif isinstance(exc, ssl.SSLError):
241
+ reason = "handshake_failed"
242
+ else:
243
+ reason = socket_reason(exc)
244
+ return MailError(f"TLS negotiation with the {protocol.upper()} server failed.",
245
+ protocol, "tls", reason=reason, **details)
246
+
247
+
248
+ class _ProxyReply(Exception):
249
+ def __init__(self, reason, **details):
250
+ self.details = {"reason": reason, **details}
251
+
252
+
253
+ class _Negotiation:
254
+ """Read exactly the proxy reply, with a deadline for the entire handshake."""
255
+
256
+ def __init__(self, sock, timeout):
257
+ self.sock = sock
258
+ self.deadline = time.monotonic() + timeout
259
+
260
+ def _set_timeout(self):
261
+ remaining = self.deadline - time.monotonic()
262
+ if remaining <= 0:
263
+ raise TimeoutError()
264
+ self.sock.settimeout(remaining)
265
+
266
+ def send(self, payload):
267
+ self._set_timeout()
268
+ self.sock.sendall(payload)
269
+
270
+ def read(self, length):
271
+ data = bytearray()
272
+ while len(data) < length:
273
+ self._set_timeout()
274
+ chunk = self.sock.recv(length - len(data))
275
+ if not chunk:
276
+ raise _ProxyReply("connection_closed")
277
+ data.extend(chunk)
278
+ return bytes(data)
279
+
280
+ def http_headers(self):
281
+ data = bytearray()
282
+ # Reading ahead could consume an SMTP greeting following CONNECT's reply.
283
+ while not data.endswith(b"\r\n\r\n"):
284
+ if len(data) >= 16384:
285
+ raise _ProxyReply("invalid_response")
286
+ data.extend(self.read(1))
287
+ return bytes(data)
288
+
289
+
290
+ def _http_connect(wire, proxy, host, port):
291
+ authority = _authority(host, port)
292
+ request = f"CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n".encode("ascii")
293
+ if proxy.auth:
294
+ request += b"Proxy-Authorization: Basic " + base64.b64encode(b":".join(proxy.auth)) + b"\r\n"
295
+ wire.send(request + b"\r\n")
296
+ for _ in range(4):
297
+ first_line = wire.http_headers().split(b"\r\n", 1)[0]
298
+ match = re.fullmatch(rb"HTTP/1\.[01] ([1-5][0-9]{2})(?: [^\r\n]*)?", first_line)
299
+ if not match:
300
+ break
301
+ status = int(match[1])
302
+ if 200 <= status < 300:
303
+ return
304
+ if status >= 300:
305
+ raise _ProxyReply("authentication_required" if status == 407 else "tunnel_rejected", http_status=status)
306
+ raise _ProxyReply("invalid_response")
307
+
308
+
309
+ _SOCKS_ERRORS = {
310
+ 1: "server_failure", 2: "tunnel_rejected", 3: "network_unreachable",
311
+ 4: "host_unreachable", 5: "connection_refused", 6: "ttl_expired",
312
+ 7: "command_unsupported", 8: "address_unsupported",
313
+ }
314
+
315
+
316
+ def _socks_address(host):
317
+ try:
318
+ addr = ipaddress.ip_address(host)
319
+ except ValueError:
320
+ name = host.encode("ascii")
321
+ return bytes((3, len(name))) + name
322
+ return bytes((1 if addr.version == 4 else 4,)) + addr.packed
323
+
324
+
325
+ def _socks_connect(wire, proxy, host, port):
326
+ method = 2 if proxy.auth else 0
327
+ wire.send(bytes((5, 1, method)))
328
+ version, selected = wire.read(2)
329
+ if version != 5:
330
+ raise _ProxyReply("invalid_response")
331
+ if selected != method:
332
+ raise _ProxyReply("authentication_required" if selected == 255 else "invalid_response")
333
+ if proxy.auth:
334
+ user, password = proxy.auth
335
+ wire.send(bytes((1, len(user))) + user + bytes((len(password),)) + password)
336
+ version, status = wire.read(2)
337
+ if version != 1:
338
+ raise _ProxyReply("invalid_response")
339
+ if status:
340
+ raise _ProxyReply("authentication_failed")
341
+ wire.send(b"\x05\x01\x00" + _socks_address(host) + struct.pack("!H", port))
342
+ version, status, reserved, kind = wire.read(4)
343
+ if version != 5 or reserved:
344
+ raise _ProxyReply("invalid_response")
345
+ if status:
346
+ raise _ProxyReply(_SOCKS_ERRORS.get(status, "tunnel_rejected"), socks_status=status)
347
+ length = wire.read(1)[0] if kind == 3 else {1: 4, 4: 16}.get(kind, 0)
348
+ if not length:
349
+ raise _ProxyReply("invalid_response")
350
+ wire.read(length + 2)
351
+
352
+
353
+ class MailSocket:
354
+ def __init__(self, protocol, context):
355
+ self.protocol = protocol
356
+ self.context = context
357
+
358
+ def open(self, host, port, timeout, *, tls):
359
+ proxy, fixed = _select_proxy(self.protocol, host, port)
360
+ path = _cache_path(host, port)
361
+ cached = _cached_route(path, proxy) if proxy and not fixed else None
362
+ first = proxy if proxy and (fixed or cached == "proxy" or
363
+ (cached is None and _resolves_to_fake_ip(host, port))) else None
364
+ try:
365
+ return self._connect(host, port, timeout, tls, first, path)
366
+ except MailError as error:
367
+ if not proxy and not fixed and (_retryable(error, None) or error.details.get("stage") == "dns"):
368
+ error.details["hint"] = _NO_PROXY_HINT
369
+ if (not proxy or fixed or not _retryable(error, first)
370
+ or (first and (cached != "proxy" or _resolves_to_fake_ip(host, port)))):
371
+ raise
372
+ fallback = None if first else proxy
373
+ LOG.debug("protocol=%s via=%s fallback_reason=%s", self.protocol,
374
+ _route_fields(fallback)["via"], error.details.get("reason"))
375
+ try:
376
+ return self._connect(host, port, timeout, tls, fallback, path)
377
+ except MailError as final:
378
+ final.details["attempts"] = [_attempt_fields(error), _attempt_fields(final)]
379
+ raise final from None
380
+
381
+ def _connect(self, host, port, timeout, tls, proxy, path):
382
+ fields = _route_fields(proxy)
383
+ try:
384
+ sock = self._open_route(host, port, timeout, tls, proxy)
385
+ except MailError as error:
386
+ error.details.update(fields)
387
+ raise
388
+ _save_route(path, fields)
389
+ report = _route_report.get()
390
+ if report is not None and (not report or proxy):
391
+ report.update(fields)
392
+ return sock
393
+
394
+ def _open_route(self, host, port, timeout, tls, proxy):
395
+ peer = "proxy" if proxy else "mail_server"
396
+ address = (proxy.host, proxy.port) if proxy else (host, port)
397
+ try:
398
+ sock = socket.create_connection(address, timeout=timeout)
399
+ except socket.gaierror:
400
+ raise MailError(f"Could not resolve the {peer.replace('_', ' ')} hostname.",
401
+ self.protocol, "dns", peer=peer, reason="resolution_failed") from None
402
+ except OSError as exc:
403
+ raise MailError(f"Could not open a TCP connection to the {peer.replace('_', ' ')}.",
404
+ self.protocol, "tcp", peer=peer, reason=socket_reason(exc)) from None
405
+ try:
406
+ if proxy:
407
+ if "%" in host or any(c.isspace() for c in host):
408
+ raise MailError("The mail server address cannot be sent through this proxy.", self.protocol,
409
+ "proxy", reason="unsupported_target")
410
+ self._tunnel(sock, proxy, host, port, timeout)
411
+ if tls:
412
+ try:
413
+ sock = self.context.wrap_socket(sock, server_hostname=host)
414
+ except OSError as exc:
415
+ raise tls_error(self.protocol, exc) from None
416
+ LOG.debug("protocol=%s route=%s stage=%s outcome=connected",
417
+ self.protocol, proxy.scheme if proxy else "direct", "tls" if tls else "tcp")
418
+ return sock
419
+ except BaseException:
420
+ with suppress(OSError):
421
+ sock.close()
422
+ raise
423
+
424
+ def _tunnel(self, sock, proxy, host, port, timeout):
425
+ kind = proxy.scheme
426
+ negotiate = _http_connect if kind == "http" else _socks_connect
427
+ try:
428
+ negotiate(_Negotiation(sock, timeout), proxy, host, port)
429
+ sock.settimeout(timeout)
430
+ except _ProxyReply as exc:
431
+ raise MailError("The proxy could not open a tunnel to the mail server.",
432
+ self.protocol, "proxy", proxy_type=kind, **exc.details) from None
433
+ except OSError as exc:
434
+ raise MailError("The proxy negotiation did not complete.", self.protocol, "proxy",
435
+ proxy_type=kind, reason=socket_reason(exc)) from None
436
+ LOG.debug("protocol=%s route=%s stage=proxy outcome=connected", self.protocol, kind)
@@ -0,0 +1,53 @@
1
+ """Read the visible text from an HTML email without loading its resources."""
2
+
3
+ import re
4
+ from html.parser import HTMLParser
5
+
6
+ from .errors import MacoError
7
+
8
+
9
+ _HIDDEN = frozenset({"head", "script", "style", "template", "noscript"})
10
+ _BREAK = frozenset({
11
+ "address", "article", "blockquote", "br", "dd", "div", "dl", "dt", "footer",
12
+ "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "li", "p", "pre",
13
+ "section", "table", "tr",
14
+ })
15
+
16
+
17
+ class _EmailText(HTMLParser):
18
+ def __init__(self):
19
+ super().__init__(convert_charrefs=True)
20
+ self.parts = []
21
+ self.hidden = []
22
+
23
+ def handle_starttag(self, tag, attrs):
24
+ if tag in _HIDDEN:
25
+ self.hidden.append(tag)
26
+ elif not self.hidden:
27
+ if tag in _BREAK:
28
+ self.parts.append("\n")
29
+ elif tag in ("td", "th"):
30
+ self.parts.append(" ")
31
+
32
+ def handle_endtag(self, tag):
33
+ if self.hidden:
34
+ if tag == self.hidden[-1]:
35
+ self.hidden.pop()
36
+ elif tag in _BREAK:
37
+ self.parts.append("\n")
38
+
39
+ def handle_data(self, data):
40
+ if not self.hidden:
41
+ self.parts.append(re.sub(r"\s+", " ", data))
42
+
43
+
44
+ def body_text(body, body_type):
45
+ if not body or body_type != "text/html":
46
+ return body
47
+ parser = _EmailText()
48
+ try:
49
+ parser.feed(body)
50
+ parser.close()
51
+ except AssertionError:
52
+ raise MacoError("Could not parse the message's HTML body.") from None
53
+ return "\n".join(line.strip() for line in "".join(parser.parts).splitlines() if line.strip())
maco_cli/oauth.py ADDED
@@ -0,0 +1,139 @@
1
+ """Microsoft public-client device authorization. All token requests are over HTTPS."""
2
+ import hashlib
3
+ import json
4
+ import time
5
+ from urllib.error import HTTPError, URLError
6
+ from urllib.parse import urlencode, urlsplit
7
+ from urllib.request import Request, urlopen
8
+
9
+ from .accounts import _directory, _locked, _read_private, _write_private
10
+ from .errors import MacoError
11
+
12
+
13
+ SCOPES = "offline_access https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send"
14
+
15
+
16
+ def _paths(account):
17
+ # Changes of account identity or client registration require a fresh login.
18
+ identity = [account.name, account.email, account.username, account.client_id, account.tenant]
19
+ key = hashlib.sha256(json.dumps(identity).encode("utf-8")).hexdigest()
20
+ root = _directory()
21
+ return root / f"oauth-{key}.cache", root / f"oauth-{key}.lock"
22
+
23
+
24
+ def _post(account, endpoint, fields):
25
+ url = f"https://login.microsoftonline.com/{account.tenant}/oauth2/v2.0/{endpoint}"
26
+ req = Request(url, data=urlencode(dict(fields, client_id=account.client_id)).encode("ascii"),
27
+ headers={"Accept": "application/json"})
28
+ try:
29
+ with urlopen(req, timeout=30) as response:
30
+ raw = response.read(1024 * 1024 + 1)
31
+ except HTTPError as exc:
32
+ with exc:
33
+ raw = exc.read(1024 * 1024 + 1)
34
+ # Only recognize documented flow errors when HTTP itself reports failure.
35
+ try:
36
+ failure = json.loads(raw)
37
+ except (ValueError, UnicodeError):
38
+ failure = {}
39
+ if isinstance(failure, dict) and isinstance(failure.get("error"), str):
40
+ return {"error": failure["error"]}
41
+ raise MacoError("Microsoft rejected the OAuth request.") from None
42
+ except (URLError, OSError):
43
+ raise MacoError("Could not reach the Microsoft sign-in service.") from None
44
+ try:
45
+ value = json.loads(raw)
46
+ if len(raw) > 1024 * 1024 or not isinstance(value, dict):
47
+ raise ValueError()
48
+ return value
49
+ except (ValueError, UnicodeError):
50
+ raise MacoError("Invalid response from Microsoft sign-in.") from None
51
+
52
+
53
+ def _required(value, key):
54
+ field = value.get(key)
55
+ if not isinstance(field, str) or not field or not field.isprintable():
56
+ raise MacoError("Microsoft sign-in returned incomplete credentials.")
57
+ return field
58
+
59
+
60
+ def _positive_int(value):
61
+ try:
62
+ number = int(value)
63
+ if number > 0:
64
+ return number
65
+ except (ValueError, TypeError, OverflowError):
66
+ pass
67
+ raise MacoError("Microsoft sign-in returned an invalid expiry or polling interval.")
68
+
69
+
70
+ def _save(path, reply, old_refresh=None):
71
+ if _required(reply, "token_type").lower() != "bearer":
72
+ raise MacoError("Microsoft sign-in did not return a bearer token.")
73
+ cache = {
74
+ "access_token": _required(reply, "access_token"),
75
+ "refresh_token": _required(reply, "refresh_token") if reply.get("refresh_token") or not old_refresh else old_refresh,
76
+ "expires_at": time.time() + _positive_int(reply.get("expires_in")),
77
+ }
78
+ data = json.dumps(cache).encode("utf-8")
79
+ _write_private(path, data)
80
+ return cache["access_token"]
81
+
82
+
83
+ def device_login(account, notify):
84
+ reply = _post(account, "devicecode", {"scope": SCOPES})
85
+ if "error" in reply:
86
+ raise MacoError("Device authorization failed. Check the tenant, client ID and public client settings.")
87
+ device_code = _required(reply, "device_code")
88
+ code = _required(reply, "user_code")
89
+ uri = _required(reply, "verification_uri")
90
+ if urlsplit(uri).scheme != "https":
91
+ raise MacoError("Microsoft sign-in returned an invalid verification URI.")
92
+ remaining = _positive_int(reply.get("expires_in"))
93
+ interval = _positive_int(reply.get("interval", 5))
94
+ deadline = time.monotonic() + remaining
95
+ notify(f"Open {uri} and enter {code} to sign in to Microsoft.")
96
+ while time.monotonic() + interval < deadline:
97
+ time.sleep(interval)
98
+ result = _post(account, "token", {"device_code": device_code, "grant_type": "urn:ietf:params:oauth:grant-type:device_code"})
99
+ error = result.get("error")
100
+ if error == "authorization_pending":
101
+ continue
102
+ if error == "slow_down":
103
+ interval += 5
104
+ continue
105
+ if error:
106
+ raise MacoError("Microsoft device login was declined or expired. Start login again.")
107
+ path, lock = _paths(account)
108
+ with _locked(lock):
109
+ _save(path, result)
110
+ return
111
+ raise MacoError("The Microsoft sign-in code expired. Start login again.")
112
+
113
+
114
+ def access_token(account):
115
+ path, lock = _paths(account)
116
+ with _locked(lock):
117
+ try:
118
+ cache = json.loads(_read_private(path))
119
+ if not isinstance(cache, dict):
120
+ raise ValueError()
121
+ refresh = _required(cache, "refresh_token")
122
+ if time.time() + 90 < float(cache["expires_at"]):
123
+ return _required(cache, "access_token")
124
+ except FileNotFoundError:
125
+ raise MacoError("Sign in to Microsoft using the login command first.") from None
126
+ except (ValueError, TypeError, KeyError, UnicodeError):
127
+ raise MacoError("Invalid Microsoft credential cache. Sign in again.") from None
128
+ result = _post(account, "token", {"grant_type": "refresh_token", "refresh_token": refresh, "scope": SCOPES})
129
+ if "error" in result:
130
+ if result["error"] == "invalid_grant":
131
+ raise MacoError("Microsoft authorization expired or was revoked. Sign in again.")
132
+ raise MacoError("Microsoft could not refresh authorization. Retry or sign in again.")
133
+ return _save(path, result, refresh)
134
+
135
+
136
+ def clear_cache(account):
137
+ path, lock = _paths(account)
138
+ with _locked(lock):
139
+ path.unlink(missing_ok=True)