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,197 @@
1
+ """Browser-approved Agent login, including split start/finish for headless agents."""
2
+ import re
3
+ import secrets
4
+ import time
5
+ from dataclasses import replace
6
+ from uuid import UUID
7
+
8
+ from . import accounts, device_store, helper_client
9
+ from .errors import MacoError
10
+ from .mail_socket import capture_route
11
+
12
+
13
+ DEFAULT_HELPER = "https://macomail.app/cli"
14
+ DISPLAY_CODE = re.compile(r"[A-HJ-NP-Z2-9]{4}(?:-[A-HJ-NP-Z2-9]{4}){2}")
15
+
16
+
17
+ def start(name=None, origin=DEFAULT_HELPER):
18
+ origin = accounts.helper_base_url(origin)
19
+ if name is not None:
20
+ accounts.profile_name(name)
21
+ if any(p.name.casefold() == name.casefold() for p in accounts.list_accounts()):
22
+ raise MacoError("An account with this name already exists.")
23
+ reply = helper_client._post(origin, None, "/v1/device/start", {})
24
+ try:
25
+ code, private_code = reply["user_code"], reply["device_code"]
26
+ url, expiry, interval = reply["verification_uri_complete"], reply["expires_in"], reply["interval"]
27
+ if (not DISPLAY_CODE.fullmatch(code) or not device_store.DEVICE_CODE.fullmatch(private_code)
28
+ or url != origin + "/?device=" + code or type(expiry) is not int or not 1 <= expiry <= 3600
29
+ or type(interval) is not int or not 1 <= interval <= expiry):
30
+ raise ValueError()
31
+ except (KeyError, TypeError, ValueError):
32
+ raise MacoError("Maco Mail Helper returned an invalid login link.") from None
33
+ request_id = secrets.token_hex(16)
34
+ now = int(time.time())
35
+ with device_store.update() as state:
36
+ requests = state["requests"]
37
+ for key in [key for key, entry in requests.items() if entry["expires_at"] <= now]:
38
+ del requests[key]
39
+ requests[request_id] = {"origin": origin, "name": name, "device_code": private_code,
40
+ "expires_at": now + expiry, "installed": {}, "complete": False}
41
+ return {"status": "pending", "request_id": request_id, "verification_uri_complete": url,
42
+ "user_code": code, "expires_in": expiry, "interval": interval}
43
+
44
+
45
+ def _grants(reply):
46
+ try:
47
+ grants = reply["grants"]
48
+ if not isinstance(grants, list) or not 1 <= len(grants) <= 16:
49
+ raise ValueError()
50
+ seen = set()
51
+ for entry in grants:
52
+ grant_id = str(UUID(entry["id"]))
53
+ UUID(entry["mailbox_id"])
54
+ token = helper_client.agent_grant(entry["agent_token"])
55
+ scope = entry["protocols"]
56
+ if (grant_id in seen or token in seen or not isinstance(scope, list) or not scope
57
+ or any(p not in ("imap", "smtp", "gmail", "outlook") for p in scope)
58
+ or len(set(scope)) != len(scope)):
59
+ raise ValueError()
60
+ seen.update((grant_id, token))
61
+ return grants
62
+ except (TypeError, KeyError, AttributeError, ValueError):
63
+ raise MacoError("Maco Mail Helper returned invalid mailbox grants.") from None
64
+
65
+
66
+ def _available_name(base, position, taken):
67
+ while True:
68
+ suffix = "" if position == 1 else f"-{position}"
69
+ candidate = base[:64 - len(suffix)] + suffix
70
+ if candidate.casefold() not in taken:
71
+ return candidate
72
+ position += 1
73
+
74
+
75
+ def _result(state, request_id, routes=None):
76
+ request = state["requests"][request_id]
77
+ routes = routes or {}
78
+ profiles = [{**state["profiles"][name]["profile"], **routes.get(grant_id, {})}
79
+ for grant_id, name in request["installed"].items()]
80
+ return {"status": "approved", "request_id": request_id, "accounts": profiles}
81
+
82
+
83
+ def _complete(request_id, state, routes=None):
84
+ request = state["requests"][request_id]
85
+ result = _result(state, request_id, routes)
86
+ if request["device_code"] is not None:
87
+ try:
88
+ ack = helper_client._post(request["origin"], None, "/v1/device/ack", {"device_code": request["device_code"]})
89
+ if ack.get("status") != "complete":
90
+ return result
91
+ except MacoError:
92
+ # Profiles are durable. Another finish can retry the acknowledgement until expiry.
93
+ return result
94
+ with device_store.update() as current:
95
+ if request_id in current["requests"]:
96
+ current["requests"][request_id]["device_code"] = None
97
+ return result
98
+
99
+
100
+ def _require_request(state, request_id):
101
+ request = state["requests"].get(request_id)
102
+ if request is None:
103
+ raise MacoError("Unknown or expired login request. Run maco account login --start again.")
104
+ return request
105
+
106
+
107
+ def _stop(request_id, message):
108
+ with device_store.update() as state:
109
+ request = _require_request(state, request_id)
110
+ if not request["complete"]:
111
+ del state["requests"][request_id]
112
+ if request["complete"]:
113
+ return _complete(request_id, state)
114
+ raise MacoError(message)
115
+
116
+
117
+ def finish(request_id=None):
118
+ if request_id is not None and not device_store.REQUEST_ID.fullmatch(request_id):
119
+ raise MacoError("Use the request_id printed by maco account login --start.")
120
+ state = device_store.load()
121
+ if request_id is None:
122
+ requests = state["requests"]
123
+ now = time.time()
124
+ request_id = next((key for key in reversed(requests)
125
+ if not requests[key]["complete"] and requests[key]["expires_at"] > now), None)
126
+ if request_id is None:
127
+ raise MacoError("No pending login request. Run maco account login --start.")
128
+ request = _require_request(state, request_id)
129
+ if request["complete"]:
130
+ return _complete(request_id, state)
131
+ if request["expires_at"] <= time.time():
132
+ return _stop(request_id, "The login link expired. Run maco account login again.")
133
+ reply = helper_client._post(request["origin"], None, "/v1/device/poll", {"device_code": request["device_code"]})
134
+ status = reply.get("status")
135
+ if status == "pending":
136
+ return {"status": status, "request_id": request_id}
137
+ if status in ("expired", "denied"):
138
+ return _stop(request_id, f"Browser login was {status}. Run maco account login again.")
139
+ if status == "complete":
140
+ latest = device_store.load()
141
+ if _require_request(latest, request_id)["complete"]:
142
+ return _complete(request_id, latest)
143
+ if status != "approved":
144
+ raise MacoError("Maco Mail Helper returned an invalid login status.")
145
+
146
+ grants = _grants(reply)
147
+ verified, failures = [], []
148
+ routes = {}
149
+ for position, entry in enumerate(grants, 1):
150
+ if entry["id"] in request["installed"]:
151
+ continue
152
+ try:
153
+ with capture_route() as route:
154
+ profile = helper_client.connect_grant(
155
+ request["name"] or "mailbox", request["origin"], entry["agent_token"],
156
+ mailbox_id=entry["mailbox_id"], protocols=entry["protocols"])
157
+ verified.append((position, entry, profile))
158
+ routes[entry["id"]] = route
159
+ except MacoError as exc:
160
+ failures.append({"mailbox_id": entry["mailbox_id"], "message": str(exc),
161
+ **getattr(exc, "details", {})})
162
+
163
+ # Publish profiles, grants and this request's progress together. A retry after a
164
+ # lost response skips installed grants even if another process finished first.
165
+ with device_store.update() as current:
166
+ request = _require_request(current, request_id)
167
+ taken = {name.casefold() for name in current["profiles"]}
168
+ taken.update(p.name.casefold() for p in accounts._manual_accounts())
169
+ for position, entry, profile in verified:
170
+ if request["complete"] or entry["id"] in request["installed"]:
171
+ continue
172
+ base = request["name"] or re.sub(r"[^A-Za-z0-9_.-]+", "-", profile.email).strip("._-") or "mailbox"
173
+ name = _available_name(base, position if request["name"] else 1, taken)
174
+ taken.add(name.casefold())
175
+ current["profiles"][name] = {"profile": accounts.public_account(replace(profile, name=name)),
176
+ "agent_token": entry["agent_token"]}
177
+ request["installed"][entry["id"]] = name
178
+ if not request["complete"]:
179
+ request["complete"] = all(entry["id"] in request["installed"] for entry in grants)
180
+
181
+ if request["complete"]:
182
+ return _complete(request_id, current, routes)
183
+ error = MacoError(f"Some mailboxes could not be connected. Retry with maco account login --finish {request_id}.")
184
+ error.details = dict(_result(current, request_id, routes), status="partial", failed=failures)
185
+ raise error
186
+
187
+
188
+ def login(name, origin, notify):
189
+ started = start(name, origin)
190
+ request_id = started["request_id"]
191
+ notify(f"Open {started['verification_uri_complete']} and confirm code {started['user_code']}.\n"
192
+ f"You can resume with maco account login --finish {request_id}.")
193
+ while True:
194
+ time.sleep(started["interval"])
195
+ result = finish(request_id)
196
+ if result["status"] != "pending":
197
+ return result
@@ -0,0 +1,69 @@
1
+ """Local, user-private grants and resumable browser login requests."""
2
+ import json
3
+ import re
4
+ from contextlib import contextmanager
5
+
6
+ from .accounts import Account, _directory, _locked, _read_private, _write_private, helper_base_url, profile_name
7
+ from .errors import MacoError
8
+ from .helper_client import agent_grant
9
+
10
+
11
+ DEVICE_CODE = re.compile(r"[A-Za-z0-9_-]{43}")
12
+ REQUEST_ID = re.compile(r"[a-f0-9]{32}")
13
+
14
+
15
+ def _load(path):
16
+ try:
17
+ data = json.loads(_read_private(path))
18
+ if (not isinstance(data, dict) or data.get("version") != 1 or
19
+ not isinstance(data["profiles"], dict) or not isinstance(data["requests"], dict)):
20
+ raise ValueError()
21
+ for name, entry in data["profiles"].items():
22
+ profile = Account(**entry["profile"])
23
+ if profile.name != name or profile.auth != "helper" or profile.agent_token_env is not None:
24
+ raise ValueError()
25
+ agent_grant(entry["agent_token"])
26
+ for request_id, request in data["requests"].items():
27
+ if (not REQUEST_ID.fullmatch(request_id) or type(request["complete"]) is not bool
28
+ or type(request["expires_at"]) is not int or not isinstance(request["installed"], dict)
29
+ or any(name not in data["profiles"] for name in request["installed"].values())):
30
+ raise ValueError()
31
+ if request["name"] is not None:
32
+ profile_name(request["name"])
33
+ helper_base_url(request["origin"])
34
+ if request["device_code"] is None:
35
+ if not request["complete"]:
36
+ raise ValueError()
37
+ elif not DEVICE_CODE.fullmatch(request["device_code"]):
38
+ raise ValueError()
39
+ return data
40
+ except FileNotFoundError:
41
+ return {"version": 1, "profiles": {}, "requests": {}}
42
+ except (TypeError, ValueError, KeyError, RecursionError):
43
+ raise MacoError("Invalid Maco browser login cache.") from None
44
+
45
+
46
+ def load():
47
+ return _load(_directory() / "device-login.cache")
48
+
49
+
50
+ @contextmanager
51
+ def update():
52
+ root = _directory()
53
+ # The same lock guards manual profiles so a late login cannot take their names.
54
+ with _locked(root / "accounts.lock"):
55
+ path = root / "device-login.cache"
56
+ state = _load(path)
57
+ yield state
58
+ _write_private(path, json.dumps(state, ensure_ascii=False).encode("utf-8"))
59
+
60
+
61
+ def linked_accounts():
62
+ return [Account(**entry["profile"]) for entry in load()["profiles"].values()]
63
+
64
+
65
+ def stored_grant(account):
66
+ entry = load()["profiles"].get(account.name)
67
+ if entry is None or Account(**entry["profile"]) != account:
68
+ raise MacoError("The saved grant does not match this mailbox. Run maco account login again.")
69
+ return entry["agent_token"]
maco_cli/errors.py ADDED
@@ -0,0 +1,10 @@
1
+ class MacoError(Exception):
2
+ """An operational error whose message is safe to display to the caller."""
3
+
4
+
5
+ class MailError(MacoError):
6
+ """A mail failure with safe, machine-readable diagnostics."""
7
+
8
+ def __init__(self, message, protocol, stage, **details):
9
+ super().__init__(message)
10
+ self.details = {"protocol": protocol, "stage": stage, **details}
maco_cli/gmail_api.py ADDED
@@ -0,0 +1,210 @@
1
+ """Mailbox operations using the Gmail API and Gmail's native message and label IDs."""
2
+ import base64
3
+ from email import policy
4
+ from email.message import EmailMessage
5
+ from urllib.parse import quote
6
+
7
+ from .errors import MacoError
8
+ from .incoming import message_headers
9
+ from .mail_query import phrases, utc_seconds
10
+
11
+
12
+ _HEADERS = ("From", "To", "Cc", "Reply-To", "Subject", "Date", "Message-ID", "References")
13
+ _SYSTEM_LABELS = {
14
+ "INBOX", "SPAM", "TRASH", "UNREAD", "STARRED", "IMPORTANT", "SENT", "DRAFT",
15
+ "CATEGORY_PERSONAL", "CATEGORY_SOCIAL", "CATEGORY_PROMOTIONS", "CATEGORY_UPDATES", "CATEGORY_FORUMS",
16
+ }
17
+ _LABEL_CHANGES = {
18
+ "read": ("removeLabelIds", "UNREAD"),
19
+ "unread": ("addLabelIds", "UNREAD"),
20
+ "flag": ("addLabelIds", "STARRED"),
21
+ "unflag": ("removeLabelIds", "STARRED"),
22
+ "archive": ("removeLabelIds", "INBOX"),
23
+ }
24
+
25
+
26
+ def _message_path(message_id):
27
+ if not isinstance(message_id, str) or not message_id or message_id in (".", ".."):
28
+ raise MacoError("A Gmail message ID is required.")
29
+ return "messages/" + quote(message_id, safe="")
30
+
31
+
32
+ def _quoted(value):
33
+ if any(ord(c) < 32 or ord(c) == 127 for c in value):
34
+ raise MacoError("Gmail search terms must not contain control characters.")
35
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
36
+
37
+
38
+ def _search_query(sender, subject, text, after, before, scope):
39
+ terms = []
40
+ for prefix, value in (("from:", sender), ("subject:", subject)):
41
+ if value:
42
+ terms.append(prefix + _quoted(value))
43
+ prefix = scope + ":" if scope in ("from", "subject") else ""
44
+ alternatives = [prefix + _quoted(phrase) for phrase in phrases(text)]
45
+ if alternatives:
46
+ terms.append(alternatives[0] if len(alternatives) == 1 else "{" + " ".join(alternatives) + "}")
47
+ if after:
48
+ terms.append(f"after:{utc_seconds(after)}")
49
+ if before:
50
+ terms.append(f"before:{utc_seconds(before)}")
51
+ return " ".join(terms)
52
+
53
+
54
+ def _summary(item):
55
+ message = EmailMessage(policy=policy.default)
56
+ payload = item.get("payload", {})
57
+ headers = payload.get("headers", []) if isinstance(payload, dict) else None
58
+ if not isinstance(headers, list):
59
+ raise MacoError("Gmail returned invalid message headers.")
60
+ for header in headers:
61
+ if not isinstance(header, dict) or not all(isinstance(header.get(key), str) for key in ("name", "value")):
62
+ raise MacoError("Gmail returned invalid message headers.")
63
+ message.set_raw(header["name"], header["value"])
64
+ labels = item.get("labelIds", [])
65
+ if not isinstance(labels, list) or any(not isinstance(label, str) for label in labels):
66
+ raise MacoError("Gmail returned invalid message labels.")
67
+ flags = [] if "UNREAD" in labels else [r"\Seen"]
68
+ if "STARRED" in labels:
69
+ flags.append(r"\Flagged")
70
+ return {
71
+ "id": item["id"], "thread_id": item.get("threadId"), "labels": labels, "flags": flags,
72
+ **message_headers(message),
73
+ }
74
+
75
+
76
+ class GmailAPI:
77
+ def __init__(self, http):
78
+ self.http = http
79
+
80
+ def check(self):
81
+ profile = self.http.request("GET", "profile", params={"fields": "emailAddress"})
82
+ if not isinstance(profile.get("emailAddress"), str):
83
+ raise MacoError("Gmail returned an invalid mailbox profile.")
84
+ return {"status": "authenticated", "protocols": ["gmail"], "email": profile["emailAddress"]}
85
+
86
+ def folders(self):
87
+ labels = self.http.request("GET", "labels", params={"fields": "labels(id,name,type)"})
88
+ rows = labels.get("labels", [])
89
+ if not isinstance(rows, list) or any(not isinstance(row, dict) or
90
+ not all(isinstance(row.get(key), str) for key in ("id", "name")) for row in rows):
91
+ raise MacoError("Gmail returned an invalid label list.")
92
+ return {"folders": rows}
93
+
94
+ def _label_id(self, folder):
95
+ if not folder:
96
+ raise MacoError("A Gmail label ID or name is required.")
97
+ if folder.upper() in _SYSTEM_LABELS:
98
+ return folder.upper()
99
+ labels = self.folders()["folders"]
100
+ for key in ("id", "name"):
101
+ for label in labels:
102
+ if label[key] == folder:
103
+ return label["id"]
104
+ raise MacoError("Unknown Gmail label. Use folders to find its name or ID.")
105
+
106
+ def emails(self, folder="INBOX", *, limit=20, offset=0, unread=False, sender=None, subject=None, text=None,
107
+ after=None, before=None, scope="any"):
108
+ if limit < 1 or offset < 0:
109
+ raise MacoError("Limit must be positive and offset must be nonnegative.")
110
+ query = _search_query(sender, subject, text, after, before, scope)
111
+ label = self._label_id(folder)
112
+ params = {"labelIds": [label]}
113
+ if unread and label != "UNREAD":
114
+ params["labelIds"].append("UNREAD")
115
+ if label in ("SPAM", "TRASH"):
116
+ params["includeSpamTrash"] = "true"
117
+ if query:
118
+ params["q"] = query
119
+
120
+ skip = offset
121
+ messages = []
122
+ seen_pages = set()
123
+ result = {"folder": folder, "offset": offset, "messages": messages}
124
+ while len(messages) < limit:
125
+ params["maxResults"] = min(500, skip + limit - len(messages))
126
+ page = self.http.request("GET", "messages", params=params.copy())
127
+ if "pageToken" not in params and "resultSizeEstimate" in page:
128
+ result["total_estimate"] = page["resultSizeEstimate"]
129
+ items = page.get("messages", [])
130
+ if not isinstance(items, list) or any(
131
+ not isinstance(item, dict) or not isinstance(item.get("id"), str) for item in items
132
+ ):
133
+ raise MacoError("Gmail returned an invalid message list.")
134
+ paths = [_message_path(item["id"]) for item in items[skip:skip + limit - len(messages)]]
135
+ for details in self.http.get_many(paths, params={
136
+ "format": "metadata",
137
+ "metadataHeaders": list(_HEADERS),
138
+ "fields": "id,threadId,labelIds,payload/headers",
139
+ }):
140
+ if not isinstance(details.get("id"), str):
141
+ raise MacoError("Gmail returned a message without an ID.")
142
+ messages.append(_summary(details))
143
+ skip = max(0, skip - len(items))
144
+ token = page.get("nextPageToken")
145
+ if not token:
146
+ break
147
+ if not isinstance(token, str):
148
+ raise MacoError("Gmail returned an invalid page token.")
149
+ if token in seen_pages:
150
+ raise MacoError("Gmail returned a repeated page token.")
151
+ seen_pages.add(token)
152
+ params["pageToken"] = token
153
+ return result
154
+
155
+ def raw(self, message_id):
156
+ resource = self.http.request("GET", _message_path(message_id), params={"format": "raw", "fields": "raw"})
157
+ try:
158
+ raw = resource["raw"].encode("ascii")
159
+ return base64.b64decode(raw + b"=" * (-len(raw) % 4), altchars=b"-_", validate=True)
160
+ except (AttributeError, KeyError, TypeError, ValueError):
161
+ raise MacoError("Gmail returned an invalid raw message.") from None
162
+
163
+ def action(self, folder, message_id, operation, target=None):
164
+ path = _message_path(message_id)
165
+ result = {"folder": folder, "id": message_id, "action": operation}
166
+ if operation not in (*_LABEL_CHANGES, "move", "trash"):
167
+ raise MacoError(f"Unknown Gmail action: {operation}")
168
+ if target is not None and operation not in ("move", "archive", "trash"):
169
+ raise MacoError("A target label is only used for move, archive and trash.")
170
+ source = self._label_id(folder)
171
+ if operation == "move" or target is not None:
172
+ destination = self._label_id(target)
173
+ if source == destination:
174
+ raise MacoError("The destination is the selected label.")
175
+ if source in ("SENT", "DRAFT") or destination in ("SENT", "DRAFT"):
176
+ raise MacoError("Gmail manages its SENT and DRAFT labels automatically.")
177
+ changes = {"addLabelIds": [destination], "removeLabelIds": [source]}
178
+ result["target"] = target
179
+ elif operation in _LABEL_CHANGES:
180
+ modifier, label = _LABEL_CHANGES[operation]
181
+ changes = {modifier: [label]}
182
+ else:
183
+ changes = None # Gmail's trash endpoint takes an empty request body.
184
+ current = self.http.request("GET", path, params={"format": "minimal", "fields": "labelIds"})
185
+ if source not in current.get("labelIds", []):
186
+ raise MacoError("The Gmail message does not belong to the selected label.")
187
+ if changes is None:
188
+ self.http.request("POST", path + "/trash")
189
+ else:
190
+ self.http.request("POST", path + "/modify", json_body=changes)
191
+ return result
192
+
193
+ def submit(self, message, *, draft, reply_id=None):
194
+ raw = message.as_bytes(policy=policy.SMTPUTF8)
195
+ payload = {"raw": base64.urlsafe_b64encode(raw).decode("ascii")}
196
+ if reply_id is not None:
197
+ source = self.http.request("GET", _message_path(reply_id), params={"format": "minimal", "fields": "threadId"})
198
+ if not source.get("threadId"):
199
+ raise MacoError("The original Gmail message has no thread ID.")
200
+ payload["threadId"] = source["threadId"]
201
+ result = {"message_id": str(message.get("Message-ID", ""))}
202
+ if draft:
203
+ saved = self.http.request("POST", "drafts", json_body={"message": payload})
204
+ resource = saved["message"]
205
+ result.update(status="draft_saved", draft_id=saved["id"], folder="DRAFT")
206
+ else:
207
+ resource = self.http.request("POST", "messages/send", json_body=payload)
208
+ result["status"] = "sent"
209
+ result.update(id=resource["id"], thread_id=resource.get("threadId"))
210
+ return result