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.
maco_cli/graph_api.py ADDED
@@ -0,0 +1,254 @@
1
+ """Microsoft Graph mailbox operations for a delegated Outlook connection."""
2
+
3
+ import base64
4
+ import json
5
+ import re
6
+ from collections import deque
7
+ from email import policy
8
+ from email.utils import formataddr
9
+ from itertools import islice
10
+ from urllib.parse import quote, unquote, urlsplit
11
+
12
+ from .errors import MacoError
13
+ from .mail_query import midnight_utc, phrases
14
+
15
+
16
+ _FOLDERS = {name: name for name in (
17
+ "archive", "clutter", "conflicts", "conversationhistory", "deleteditems", "drafts", "inbox",
18
+ "junkemail", "localfailures", "msgfolderroot", "outbox", "recoverableitemsdeletions",
19
+ "scheduled", "searchfolders", "sentitems", "serverfailures", "syncissues",
20
+ )}
21
+ _FOLDERS.update({"trash": "deleteditems", "deleted items": "deleteditems", "sent": "sentitems",
22
+ "sent items": "sentitems", "junk": "junkemail", "junk email": "junkemail"})
23
+ _WELL_KNOWN = frozenset(_FOLDERS.values())
24
+ _HEADERS = "id,subject,from,toRecipients,ccRecipients,replyTo,internetMessageId,receivedDateTime,isRead,flag"
25
+ _ODATA_FOLDER = re.compile(r"mailFolders\('((?:[^']|'')+)'\)/(messages|childFolders)")
26
+ _SEARCH_WINDOW = 1000
27
+ _KQL_KEYWORDS = {"AND", "OR", "NOT", "NEAR", "ONEAR", "XRANK", "WORDS"}
28
+
29
+
30
+ def _segment(value):
31
+ if (not isinstance(value, str) or not value or len(value) > 4096 or value in (".", "..")
32
+ or any(ord(c) < 32 or ord(c) == 127 for c in value)):
33
+ raise MacoError("Invalid Outlook resource ID.")
34
+ return quote(value, safe="")
35
+
36
+
37
+ def _collection_path(resource):
38
+ decoded = unquote(resource)
39
+ odata = _ODATA_FOLDER.fullmatch(decoded)
40
+ if odata:
41
+ folder, child = odata.groups()
42
+ decoded = "mailFolders/" + folder.replace("''", "'") + "/" + child
43
+ parts = decoded.split("/")
44
+ if len(parts) == 3 and parts[0] == "mailFolders" and parts[1].casefold() in _WELL_KNOWN:
45
+ parts[1] = parts[1].casefold()
46
+ return "/".join(parts)
47
+ return decoded
48
+
49
+
50
+ def _continuation(link, collection):
51
+ if (not isinstance(link, str) or len(link) > 32768
52
+ or any(ord(c) <= 32 or ord(c) == 127 for c in link)):
53
+ raise MacoError("Invalid Microsoft Graph continuation URL.")
54
+ try:
55
+ url = urlsplit(link)
56
+ except ValueError:
57
+ raise MacoError("Invalid Microsoft Graph continuation URL.") from None
58
+ path = url.path.split("/")
59
+ if url.scheme != "https" or url.netloc.lower() != "graph.microsoft.com" or url.fragment or not url.query:
60
+ raise MacoError("Invalid Microsoft Graph continuation URL.")
61
+ if path[:3] == ["", "v1.0", "me"]:
62
+ resource = "/".join(path[3:])
63
+ # Rebase Graph's canonical /users/{id} links onto the account's /me route.
64
+ elif path[:3] == ["", "v1.0", "users"] and len(path) > 4 and path[3]:
65
+ resource = "/".join(path[4:])
66
+ else:
67
+ raise MacoError("Invalid Microsoft Graph continuation URL.")
68
+
69
+ if _collection_path(resource) != _collection_path(collection):
70
+ raise MacoError("Invalid Microsoft Graph continuation URL.")
71
+ return resource + "?" + url.query
72
+
73
+
74
+ def _recipient(person):
75
+ address = (person or {}).get("emailAddress") or {}
76
+ display, email = address.get("name", ""), address.get("address", "")
77
+ if not display or display == email:
78
+ return email
79
+ if not email.isascii():
80
+ return f"{display} <{email}>"
81
+ return formataddr((display, email))
82
+
83
+
84
+ def _keyword(value):
85
+ if any(ord(char) < 32 or ord(char) == 127 for char in value):
86
+ raise MacoError("Outlook search terms must not contain control characters.")
87
+ if value.isalnum() and value.upper() not in _KQL_KEYWORDS:
88
+ return value
89
+ return json.dumps(value, ensure_ascii=False)
90
+
91
+
92
+ def _search_parameters(params, *, sender, subject, text, unread, after, before, scope):
93
+ keywords = [key + ":" + _keyword(value) for key, value in (("from", sender), ("subject", subject)) if value]
94
+ prefix = scope + ":" if scope != "any" else ""
95
+ choices = [prefix + _keyword(phrase) for phrase in phrases(text)]
96
+ if choices:
97
+ keywords.append(choices[0] if len(choices) == 1 else "(" + " OR ".join(choices) + ")")
98
+ if keywords:
99
+ if after:
100
+ keywords.append("received>=" + midnight_utc(after))
101
+ if before:
102
+ keywords.append("received<" + midnight_utc(before))
103
+ params["$search"] = json.dumps(" AND ".join(keywords), ensure_ascii=False)
104
+ return
105
+
106
+ filters = []
107
+ if after:
108
+ filters.append("receivedDateTime ge " + midnight_utc(after))
109
+ if before:
110
+ filters.append("receivedDateTime lt " + midnight_utc(before))
111
+ if filters or not unread:
112
+ params["$orderby"] = "receivedDateTime desc"
113
+ if unread:
114
+ filters.append("isRead eq false")
115
+ if filters:
116
+ params["$filter"] = " and ".join(filters)
117
+
118
+
119
+ class GraphAPI:
120
+ def __init__(self, http):
121
+ self.http = http
122
+
123
+ def _items(self, path, params):
124
+ page = self.http.request("GET", path, params=params)
125
+ seen = set()
126
+ while True:
127
+ rows = page.get("value")
128
+ if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
129
+ raise MacoError("Invalid Microsoft Graph collection.")
130
+ yield from rows
131
+ link = page.get("@odata.nextLink")
132
+ if link is None:
133
+ return
134
+ continuation = _continuation(link, path)
135
+ if continuation in seen:
136
+ raise MacoError("Microsoft Graph returned a repeated page.")
137
+ seen.add(continuation)
138
+ page = self.http.request("GET", continuation)
139
+
140
+ def check(self):
141
+ self.http.request("GET", "mailFolders/inbox", params={"$select": "id"})
142
+ return {"status": "authenticated", "protocols": ["outlook"]}
143
+
144
+ def folders(self):
145
+ folders, seen = [], set()
146
+ pending = deque([("mailFolders", "")])
147
+ while pending:
148
+ collection, parent = pending.popleft()
149
+ for item in self._items(collection, {"$select": "id,displayName,childFolderCount", "$top": 100}):
150
+ folder_id = item.get("id")
151
+ segment = _segment(folder_id)
152
+ if folder_id in seen:
153
+ continue
154
+ seen.add(folder_id)
155
+ if not isinstance(item.get("displayName"), str):
156
+ raise MacoError("Invalid Outlook folder name.")
157
+ name = parent + item["displayName"]
158
+ folders.append({"id": folder_id, "name": name})
159
+ if item.get("childFolderCount", 0):
160
+ pending.append((f"mailFolders/{segment}/childFolders", name + "/"))
161
+ return {"folders": folders}
162
+
163
+ def _folder(self, value):
164
+ if not isinstance(value, str) or not value:
165
+ raise MacoError("Specify an Outlook folder name or ID.")
166
+ if value.casefold() in _FOLDERS:
167
+ return _FOLDERS[value.casefold()]
168
+ names = []
169
+ for folder in self.folders()["folders"]:
170
+ if folder["id"] == value:
171
+ return value
172
+ if folder["name"].casefold() == value.casefold():
173
+ names.append(folder["id"])
174
+ if len(names) != 1:
175
+ raise MacoError("Could not identify this Outlook folder. Use the ID from folders.")
176
+ return names[0]
177
+
178
+ def emails(self, folder="INBOX", *, limit=20, offset=0, unread=False, sender=None, subject=None, text=None,
179
+ after=None, before=None, scope="any"):
180
+ if limit < 1 or offset < 0:
181
+ raise MacoError("Limit must be positive and offset must be nonnegative.")
182
+ params = {"$select": _HEADERS, "$top": min(100, limit + offset)}
183
+ _search_parameters(params, sender=sender, subject=subject, text=text, unread=unread,
184
+ after=after, before=before, scope=scope)
185
+ searching = "$search" in params
186
+ if searching and offset >= _SEARCH_WINDOW:
187
+ error = MacoError("Outlook limits indexed searches to 1,000 results. Narrow the query or add a date range.")
188
+ error.details = {"provider": "outlook", "stage": "mail_api", "category": "search_window"}
189
+ raise error
190
+ path = f"mailFolders/{_segment(self._folder(folder))}/messages"
191
+ messages, matched, scanned = [], 0, 0
192
+ rows = self._items(path, params)
193
+ for scanned, row in enumerate(islice(rows, _SEARCH_WINDOW) if searching else rows, 1):
194
+ person = (row.get("from") or {}).get("emailAddress") or {}
195
+ if (unread and row.get("isRead") is not False
196
+ or sender and sender.casefold() not in (person.get("name", "") + " " + person.get("address", "")).casefold()
197
+ or subject and subject.casefold() not in (row.get("subject") or "").casefold()):
198
+ continue
199
+ matched += 1
200
+ if matched <= offset:
201
+ continue
202
+ _segment(row.get("id"))
203
+ flags = ["\\Seen"] if row.get("isRead") else []
204
+ if (row.get("flag") or {}).get("flagStatus") == "flagged":
205
+ flags.append("\\Flagged")
206
+ messages.append({"id": row["id"], "subject": row.get("subject") or "", "from": _recipient(row.get("from")),
207
+ "to": ", ".join(map(_recipient, row.get("toRecipients") or [])),
208
+ "cc": ", ".join(map(_recipient, row.get("ccRecipients") or [])),
209
+ "reply_to": ", ".join(map(_recipient, row.get("replyTo") or [])),
210
+ "date": row.get("receivedDateTime"), "message_id": row.get("internetMessageId"), "flags": flags})
211
+ if len(messages) == limit:
212
+ break
213
+ result = {"folder": folder, "offset": offset, "messages": messages}
214
+ if searching and scanned >= _SEARCH_WINDOW and len(messages) < limit:
215
+ result["truncated"] = True
216
+ return result
217
+
218
+ def raw(self, message_id):
219
+ return self.http.request("GET", f"messages/{_segment(message_id)}/$value", raw=True)
220
+
221
+ def action(self, folder, message_id, operation, target=None):
222
+ source = self._folder(folder)
223
+ path = f"mailFolders/{_segment(source)}/messages/{_segment(message_id)}"
224
+ result = {"id": message_id, "action": operation, "folder": folder}
225
+ if operation in ("read", "unread", "flag", "unflag"):
226
+ if target is not None:
227
+ raise MacoError("A target folder is only used for move, archive and trash.")
228
+ patch = ({"isRead": operation == "read"} if operation in ("read", "unread") else
229
+ {"flag": {"flagStatus": "flagged" if operation == "flag" else "notFlagged"}})
230
+ self.http.request("PATCH", path, json_body=patch)
231
+ elif operation in ("move", "archive", "trash"):
232
+ destination = target or {"archive": "archive", "trash": "deleteditems"}.get(operation)
233
+ destination_id = self._folder(destination)
234
+ if destination_id == source:
235
+ raise MacoError("The destination is the selected folder.")
236
+ moved = self.http.request("POST", path + "/move", json_body={"destinationId": destination_id})
237
+ result.update(id=moved.get("id") or message_id, target=destination)
238
+ else:
239
+ raise MacoError("Unknown Outlook message action.")
240
+ return result
241
+
242
+ def submit(self, message, *, draft, reply_id=None):
243
+ if reply_id is not None:
244
+ path = f"messages/{_segment(reply_id)}/" + ("createReply" if draft else "reply")
245
+ else:
246
+ path = "messages" if draft else "sendMail"
247
+ mime = base64.b64encode(message.as_bytes(policy=policy.SMTPUTF8))
248
+ response = self.http.request("POST", path, data=mime, content_type="text/plain")
249
+ result = {"status": "draft_saved" if draft else "accepted", "message_id": str(message.get("Message-ID", ""))}
250
+ if draft:
251
+ if not response.get("id"):
252
+ raise MacoError("Outlook returned no draft ID. Check Drafts before retrying.")
253
+ result.update(id=response["id"], draft_id=response["id"], folder="drafts")
254
+ return result
@@ -0,0 +1,204 @@
1
+ """Fetch account-bound credentials from Maco Mail Helper over verified HTTPS."""
2
+ import base64
3
+ import json
4
+ import os
5
+ import re
6
+ import ssl
7
+ import time
8
+ from dataclasses import replace
9
+ from http.client import HTTPException
10
+ from urllib.error import HTTPError, URLError
11
+ from urllib.request import HTTPRedirectHandler, HTTPSHandler, Request, build_opener
12
+ from uuid import uuid4
13
+
14
+ from . import __version__
15
+ from .accounts import Account, credential_env_name, helper_base_url
16
+ from .errors import MacoError
17
+
18
+
19
+ AAD = b"maco-mail-lease-v1"
20
+ MAX_RESPONSE = 256 * 1024
21
+ MAIL_FIELDS = ("email", "username", "imap_host", "imap_port", "smtp_host", "smtp_port", "smtp_security")
22
+
23
+
24
+ class _NoRedirect(HTTPRedirectHandler):
25
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
26
+ return None
27
+
28
+
29
+ class _ProtocolDenied(MacoError):
30
+ """Older Helpers expose a grant's protocol scope only when a lease is requested."""
31
+
32
+
33
+ def agent_grant(value):
34
+ if not isinstance(value, str) or not re.fullmatch(r"maco_agent_v1_[A-Za-z0-9_-]{43}", value):
35
+ raise MacoError("Expected an Agent grant issued by Maco Mail Helper.")
36
+ return value
37
+
38
+
39
+ def _post(origin, token, endpoint, payload):
40
+ headers = {"Accept": "application/json", "Content-Type": "application/json",
41
+ "Cache-Control": "no-store", "User-Agent": f"maco-cli/{__version__}"}
42
+ if token is not None:
43
+ headers["Authorization"] = "Bearer " + agent_grant(token)
44
+ request = Request(
45
+ helper_base_url(origin) + endpoint,
46
+ data=json.dumps(payload).encode("utf-8"),
47
+ headers=headers,
48
+ )
49
+ try:
50
+ context = ssl.create_default_context(cafile=os.environ.get("SSL_CERT_FILE") or None)
51
+ opener = build_opener(_NoRedirect(), HTTPSHandler(context=context))
52
+ with opener.open(request, timeout=30) as response:
53
+ data = response.read(MAX_RESPONSE + 1)
54
+ except HTTPError as exc:
55
+ exc.close()
56
+ if exc.code == 403 and endpoint == "/v1/lease":
57
+ failure = _ProtocolDenied("This Agent grant does not authorize this protocol.")
58
+ elif exc.code in (401, 403, 404):
59
+ failure = MacoError("Maco Mail Helper denied access. Check the Agent grant, mailbox and protocol.")
60
+ elif exc.code == 409:
61
+ failure = MacoError("The mailbox connection changed or its credential expired. Check it in Maco and create a new Agent grant if needed.")
62
+ else:
63
+ failure = MacoError(f"Maco Mail Helper returned HTTP {exc.code}.")
64
+ failure.details = {"service": "maco_helper", "http_status": exc.code}
65
+ raise failure from None
66
+ except (OSError, URLError, HTTPException):
67
+ raise MacoError("Could not establish a verified connection to Maco Mail Helper.") from None
68
+ try:
69
+ if len(data) > MAX_RESPONSE:
70
+ raise ValueError()
71
+ value = json.loads(data)
72
+ if not isinstance(value, dict):
73
+ raise ValueError()
74
+ return value
75
+ except (ValueError, UnicodeError, RecursionError):
76
+ raise MacoError("Invalid response from Maco Mail Helper.") from None
77
+
78
+
79
+ def _environment_grant(env_name):
80
+ token = os.environ.get(credential_env_name(env_name), "")
81
+ if not token:
82
+ raise MacoError("Set the configured environment variable with your Maco Agent grant.")
83
+ return agent_grant(token)
84
+
85
+
86
+ def connect_account(name, origin, env_name):
87
+ return connect_grant(name, origin, _environment_grant(env_name), env_name)
88
+
89
+
90
+ def connect_grant(name, origin, token, env_name=None, *, mailbox_id=None, protocols=None):
91
+ origin = helper_base_url(origin)
92
+ response = _post(origin, agent_grant(token), "/v1/connect", {})
93
+ try:
94
+ mailbox = response["mailbox"]
95
+ if not isinstance(mailbox, dict):
96
+ raise ValueError()
97
+ provider = mailbox.get("provider")
98
+ if mailbox_id is not None and mailbox["id"] != mailbox_id:
99
+ raise ValueError()
100
+ if provider in ("gmail", "outlook"):
101
+ profile = Account(name=name, auth="helper", helper_url=origin, agent_token_env=env_name,
102
+ email=mailbox["email"], mailbox_id=mailbox["id"], mailbox_auth=provider)
103
+ else:
104
+ fields = {key: mailbox[key] for key in MAIL_FIELDS}
105
+ if not isinstance(fields["username"], str):
106
+ raise ValueError()
107
+ profile = Account(name=name, auth="helper", helper_url=origin, agent_token_env=env_name,
108
+ mailbox_id=mailbox["id"], mailbox_auth=mailbox["auth"], **fields)
109
+ scope = response.get("protocols", protocols)
110
+ if scope is not None:
111
+ valid = (provider,) if provider in ("gmail", "outlook") else ("imap", "smtp")
112
+ if (not isinstance(scope, list) or not scope or any(p not in valid for p in scope)
113
+ or len(set(scope)) != len(scope) or protocols is not None and set(scope) != set(protocols)):
114
+ raise ValueError()
115
+ except (KeyError, TypeError, ValueError):
116
+ raise MacoError("Maco Mail Helper returned an invalid mailbox profile.") from None
117
+ if profile.mailbox_auth in ("gmail", "outlook"):
118
+ scope = [profile.mailbox_auth]
119
+ else:
120
+ scope = _check_mailbox(profile, token, scope)
121
+ return replace(profile, protocols=scope)
122
+
123
+
124
+ def _check_mailbox(profile, token, scope):
125
+ from .transport import check_protocol
126
+ checked = []
127
+ failures = {}
128
+ diagnostics = {}
129
+ for protocol in scope or ("imap", "smtp"):
130
+ stage = "helper_lease"
131
+ try:
132
+ secret = lease_credential(profile, protocol, grant=token)
133
+ stage = "mailbox_check"
134
+ check_protocol(profile, protocol, secret=secret)
135
+ checked.append(protocol)
136
+ except MacoError as exc:
137
+ if isinstance(exc, _ProtocolDenied) and scope is None:
138
+ continue
139
+ failures[protocol] = str(exc)
140
+ diagnostics[protocol] = {"protocol": protocol, "stage": stage, **getattr(exc, "details", {})}
141
+ except (OSError, UnicodeError):
142
+ failures[protocol] = "Could not complete this mailbox connection."
143
+ diagnostics[protocol] = {"protocol": protocol, "stage": stage}
144
+ if failures or not checked:
145
+ error = MacoError("Mailbox connection check failed. Review the failed connection stages and retry.")
146
+ error.details = {"mailbox_id": profile.mailbox_id, "email": profile.email,
147
+ "checked": checked, "protocol_errors": failures, "protocol_error_details": diagnostics}
148
+ raise error
149
+ return checked
150
+
151
+
152
+ def _decode(value):
153
+ if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_-]+={0,2}", value):
154
+ raise ValueError()
155
+ return base64.b64decode(value + "=" * (-len(value) % 4), altchars=b"-_", validate=True)
156
+
157
+
158
+ def lease_credential(account, protocol, *, grant=None):
159
+ native = account.mailbox_auth in ("gmail", "outlook")
160
+ if (native and protocol != account.mailbox_auth) or (not native and protocol not in ("imap", "smtp")):
161
+ raise MacoError("The requested protocol does not match this managed mailbox.")
162
+ if account.protocols is not None and protocol not in account.protocols:
163
+ raise MacoError("This Agent grant does not authorize this protocol.")
164
+ try:
165
+ from cryptography.exceptions import InvalidTag
166
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
167
+ except ImportError:
168
+ raise MacoError("Install the cryptography package in this Python environment to use Maco Mail Helper.") from None
169
+ request_id = str(uuid4())
170
+ expected = {"mailbox_id": account.mailbox_id, "protocol": protocol, "request_id": request_id}
171
+ if grant is None:
172
+ if account.agent_token_env is not None:
173
+ grant = _environment_grant(account.agent_token_env)
174
+ else:
175
+ from .device_store import stored_grant
176
+ grant = stored_grant(account)
177
+ envelope = _post(account.helper_url, grant, "/v1/lease", expected)
178
+ try:
179
+ if type(envelope["version"]) is not int or envelope["version"] != 1:
180
+ raise ValueError()
181
+ key = _decode(envelope["decryption_key"])
182
+ file_bytes = _decode(envelope["token_file"])
183
+ if len(key) != 32 or len(file_bytes) < 12 + 16:
184
+ raise ValueError()
185
+ clear = AESGCM(key).decrypt(file_bytes[:12], file_bytes[12:], AAD)
186
+ lease = json.loads(clear)
187
+ if not isinstance(lease, dict) or any(lease.get(k) != v for k, v in expected.items()):
188
+ raise ValueError()
189
+ if type(lease["expires_at"]) is not int or lease["expires_at"] <= time.time():
190
+ raise ValueError()
191
+ mailbox = lease["mailbox"]
192
+ if native:
193
+ pinned = dict(id=account.mailbox_id, provider=account.mailbox_auth, email=account.email)
194
+ else:
195
+ pinned = {key: getattr(account, key) for key in MAIL_FIELDS}
196
+ pinned.update(id=account.mailbox_id, auth=account.mailbox_auth)
197
+ if not isinstance(mailbox, dict) or any(mailbox.get(k) != v for k, v in pinned.items()):
198
+ raise ValueError()
199
+ secret = lease["credential"]
200
+ if not isinstance(secret, str) or not secret or not secret.isprintable():
201
+ raise ValueError()
202
+ return secret
203
+ except (KeyError, TypeError, ValueError, InvalidTag, RecursionError):
204
+ raise MacoError("The Helper credential file is invalid, expired, or does not match this request.") from None