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/__init__.py +3 -0
- maco_cli/__main__.py +4 -0
- maco_cli/accounts.py +366 -0
- maco_cli/cli.py +491 -0
- maco_cli/device_login.py +197 -0
- maco_cli/device_store.py +69 -0
- maco_cli/errors.py +10 -0
- maco_cli/gmail_api.py +210 -0
- maco_cli/graph_api.py +254 -0
- maco_cli/helper_client.py +204 -0
- maco_cli/incoming.py +440 -0
- maco_cli/mail_query.py +46 -0
- maco_cli/mail_socket.py +436 -0
- maco_cli/message_text.py +53 -0
- maco_cli/oauth.py +139 -0
- maco_cli/outgoing.py +181 -0
- maco_cli/provider.py +272 -0
- maco_cli/strict_search.py +81 -0
- maco_cli/transport.py +303 -0
- maco_cli-0.4.5.dist-info/METADATA +66 -0
- maco_cli-0.4.5.dist-info/RECORD +24 -0
- maco_cli-0.4.5.dist-info/WHEEL +5 -0
- maco_cli-0.4.5.dist-info/entry_points.txt +3 -0
- maco_cli-0.4.5.dist-info/top_level.txt +1 -0
maco_cli/__init__.py
ADDED
maco_cli/__main__.py
ADDED
maco_cli/accounts.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
"""Local account profiles and credential selection."""
|
|
2
|
+
import ipaddress
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import stat
|
|
7
|
+
import tempfile
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from dataclasses import asdict, dataclass
|
|
10
|
+
from email.errors import HeaderParseError
|
|
11
|
+
from email.headerregistry import Address
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Optional, Tuple
|
|
14
|
+
from urllib.parse import urlsplit
|
|
15
|
+
from uuid import UUID
|
|
16
|
+
|
|
17
|
+
from .errors import MacoError
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _clean(value):
|
|
21
|
+
return isinstance(value, str) and bool(value.strip()) and all(
|
|
22
|
+
c.isprintable() for c in value
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _default_env(name, auth):
|
|
27
|
+
suffix = "PASSWORD" if auth == "password" else "TOKEN"
|
|
28
|
+
prefix = re.sub(r"[^A-Z0-9]", "_", name.upper())
|
|
29
|
+
return f"MACO_{prefix}_{suffix}"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _host(value):
|
|
33
|
+
if not _clean(value):
|
|
34
|
+
raise MacoError("Invalid mail server hostname.")
|
|
35
|
+
try:
|
|
36
|
+
return str(ipaddress.ip_address(value))
|
|
37
|
+
except ValueError:
|
|
38
|
+
pass
|
|
39
|
+
try:
|
|
40
|
+
host = value.encode("idna").decode("ascii").lower()
|
|
41
|
+
except UnicodeError:
|
|
42
|
+
raise MacoError("Invalid mail server hostname.") from None
|
|
43
|
+
if len(host) > 253 or not all(
|
|
44
|
+
re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", label)
|
|
45
|
+
for label in host.split(".")
|
|
46
|
+
):
|
|
47
|
+
raise MacoError("Invalid mail server hostname.")
|
|
48
|
+
return host
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def helper_base_url(value):
|
|
52
|
+
"""Return the HTTPS Helper base, mounted at / or /cli."""
|
|
53
|
+
if not _clean(value) or any(c.isspace() or c in "\\?#" for c in value):
|
|
54
|
+
raise MacoError("Provide the HTTPS base URL of Maco Mail Helper.")
|
|
55
|
+
try:
|
|
56
|
+
url = urlsplit(value)
|
|
57
|
+
if (url.scheme != "https" or not url.hostname or url.username is not None
|
|
58
|
+
or url.password is not None or url.path not in ("", "/", "/cli", "/cli/")):
|
|
59
|
+
raise ValueError()
|
|
60
|
+
host = _host(url.hostname)
|
|
61
|
+
port = url.port
|
|
62
|
+
if port == 0:
|
|
63
|
+
raise ValueError()
|
|
64
|
+
except (TypeError, ValueError, MacoError):
|
|
65
|
+
raise MacoError("Provide the HTTPS base URL of Maco Mail Helper.") from None
|
|
66
|
+
authority = f"[{host}]" if ":" in host else host
|
|
67
|
+
return "https://" + authority + (f":{port}" if port and port != 443 else "") + url.path.rstrip("/")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def credential_env_name(value):
|
|
71
|
+
if not isinstance(value, str) or not re.fullmatch(r"[a-zA-Z_][a-zA-Z0-9_]*", value):
|
|
72
|
+
raise MacoError("Provide the name of an environment variable containing the credential.")
|
|
73
|
+
return value
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def profile_name(value):
|
|
77
|
+
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}", value):
|
|
78
|
+
raise MacoError("Use 1–64 letters, digits, hyphens, dots or underscores for the profile name.")
|
|
79
|
+
return value
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True)
|
|
83
|
+
class Account:
|
|
84
|
+
name: str
|
|
85
|
+
email: str
|
|
86
|
+
imap_host: Optional[str] = None
|
|
87
|
+
smtp_host: Optional[str] = None
|
|
88
|
+
username: Optional[str] = None
|
|
89
|
+
imap_port: int = 993
|
|
90
|
+
smtp_port: int = 465
|
|
91
|
+
smtp_security: str = "tls"
|
|
92
|
+
auth: str = "password"
|
|
93
|
+
secret_env: Optional[str] = None
|
|
94
|
+
client_id: Optional[str] = None
|
|
95
|
+
tenant: str = "common"
|
|
96
|
+
helper_url: Optional[str] = None
|
|
97
|
+
mailbox_id: Optional[str] = None
|
|
98
|
+
mailbox_auth: Optional[str] = None
|
|
99
|
+
agent_token_env: Optional[str] = None
|
|
100
|
+
protocols: Optional[Tuple[str, ...]] = None
|
|
101
|
+
|
|
102
|
+
def __post_init__(self):
|
|
103
|
+
profile_name(self.name)
|
|
104
|
+
try:
|
|
105
|
+
address = Address(addr_spec=self.email)
|
|
106
|
+
if not _clean(self.email) or not address.domain or not address.username:
|
|
107
|
+
raise ValueError()
|
|
108
|
+
except (HeaderParseError, ValueError, TypeError, IndexError, AttributeError):
|
|
109
|
+
raise MacoError("Enter a valid email address without a display name.") from None
|
|
110
|
+
username = self.email if self.username is None else self.username
|
|
111
|
+
if not _clean(username):
|
|
112
|
+
raise MacoError("A username without control characters is required.")
|
|
113
|
+
object.__setattr__(self, "username", username)
|
|
114
|
+
if self.auth not in ("password", "xoauth2", "microsoft", "helper"):
|
|
115
|
+
raise MacoError("Unknown account authentication method.")
|
|
116
|
+
if self.protocols is not None:
|
|
117
|
+
valid = (self.mailbox_auth,) if self.mailbox_auth in ("gmail", "outlook") else ("imap", "smtp")
|
|
118
|
+
if (self.auth != "helper" or not isinstance(self.protocols, (tuple, list)) or not self.protocols
|
|
119
|
+
or any(p not in valid for p in self.protocols) or len(set(self.protocols)) != len(self.protocols)):
|
|
120
|
+
raise MacoError("Invalid mailbox protocol scope.")
|
|
121
|
+
object.__setattr__(self, "protocols", tuple(self.protocols))
|
|
122
|
+
if self.auth == "helper":
|
|
123
|
+
if (self.secret_env is not None or self.client_id is not None or self.tenant != "common"
|
|
124
|
+
or self.mailbox_auth not in ("password", "xoauth2", "gmail", "outlook")
|
|
125
|
+
or not _clean(self.mailbox_id) or len(self.mailbox_id) > 255):
|
|
126
|
+
raise MacoError("Invalid managed mailbox profile. Connect the account with Maco Mail Helper.")
|
|
127
|
+
object.__setattr__(self, "helper_url", helper_base_url(self.helper_url))
|
|
128
|
+
if self.agent_token_env is not None:
|
|
129
|
+
credential_env_name(self.agent_token_env)
|
|
130
|
+
if self.mailbox_auth in ("gmail", "outlook"):
|
|
131
|
+
if self.imap_host is not None or self.smtp_host is not None:
|
|
132
|
+
raise MacoError("Provider API accounts use fixed service endpoints.")
|
|
133
|
+
return
|
|
134
|
+
object.__setattr__(self, "imap_host", _host(self.imap_host))
|
|
135
|
+
object.__setattr__(self, "smtp_host", _host(self.smtp_host))
|
|
136
|
+
if any(type(p) is not int or not (1 <= p <= 65535) for p in (self.imap_port, self.smtp_port)):
|
|
137
|
+
raise MacoError("Mail ports must be integers between 1 and 65535.")
|
|
138
|
+
if self.smtp_security not in ("tls", "starttls"):
|
|
139
|
+
raise MacoError("Choose tls or starttls for SMTP.")
|
|
140
|
+
if self.auth == "helper":
|
|
141
|
+
return
|
|
142
|
+
if any(value is not None for value in (self.helper_url, self.mailbox_id, self.mailbox_auth, self.agent_token_env)):
|
|
143
|
+
raise MacoError("Maco Mail Helper metadata requires a managed profile.")
|
|
144
|
+
if self.auth == "microsoft":
|
|
145
|
+
if self.secret_env is not None:
|
|
146
|
+
raise MacoError("Microsoft device login manages its own token cache.")
|
|
147
|
+
try:
|
|
148
|
+
client_id = str(UUID(str(self.client_id)))
|
|
149
|
+
except ValueError:
|
|
150
|
+
raise MacoError("Provide the Entra application (client) ID for device login.") from None
|
|
151
|
+
object.__setattr__(self, "client_id", client_id)
|
|
152
|
+
if not isinstance(self.tenant, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.-]{0,252}", self.tenant):
|
|
153
|
+
raise MacoError("Invalid Microsoft tenant ID or domain.")
|
|
154
|
+
if (self.imap_host != "outlook.office365.com" or self.imap_port != 993
|
|
155
|
+
or self.smtp_host not in ("smtp.office365.com", "smtp-mail.outlook.com")
|
|
156
|
+
or self.smtp_security != "starttls" or self.smtp_port != 587):
|
|
157
|
+
raise MacoError("Microsoft login requires outlook.office365.com:993 and smtp.office365.com or smtp-mail.outlook.com on port 587 with STARTTLS.")
|
|
158
|
+
else:
|
|
159
|
+
if self.client_id is not None or self.tenant != "common":
|
|
160
|
+
raise MacoError("Client ID and tenant apply to Microsoft device login.")
|
|
161
|
+
env = self.secret_env if self.secret_env is not None else _default_env(self.name, self.auth)
|
|
162
|
+
object.__setattr__(self, "secret_env", credential_env_name(env))
|
|
163
|
+
|
|
164
|
+
@property
|
|
165
|
+
def protocol_auth(self):
|
|
166
|
+
return self.mailbox_auth if self.auth == "helper" else self.auth
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _directory():
|
|
170
|
+
override = os.environ.get("MACO_CONFIG_DIR")
|
|
171
|
+
if override:
|
|
172
|
+
path = Path(override).expanduser()
|
|
173
|
+
else:
|
|
174
|
+
key = "LOCALAPPDATA" if os.name == "nt" else "XDG_CONFIG_HOME"
|
|
175
|
+
fallback = Path.home() / ("AppData/Local" if os.name == "nt" else ".config")
|
|
176
|
+
path = Path(os.environ.get(key) or fallback) / "maco"
|
|
177
|
+
path.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
178
|
+
if os.name != "nt":
|
|
179
|
+
st = path.stat()
|
|
180
|
+
if st.st_uid != os.getuid() or st.st_mode & 0o077:
|
|
181
|
+
raise MacoError("Use a private MACO_CONFIG_DIR owned by this user with permissions 0700.")
|
|
182
|
+
return path
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@contextmanager
|
|
186
|
+
def _locked(path):
|
|
187
|
+
"""OS releases the lock if a process dies. Never unlink the lock file."""
|
|
188
|
+
fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
|
|
189
|
+
with os.fdopen(fd, "r+b") as handle:
|
|
190
|
+
if os.name == "nt":
|
|
191
|
+
import msvcrt
|
|
192
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
|
|
193
|
+
else:
|
|
194
|
+
import fcntl
|
|
195
|
+
fcntl.flock(handle, fcntl.LOCK_EX)
|
|
196
|
+
try:
|
|
197
|
+
yield
|
|
198
|
+
finally:
|
|
199
|
+
if os.name == "nt":
|
|
200
|
+
handle.seek(0)
|
|
201
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
|
|
202
|
+
else:
|
|
203
|
+
fcntl.flock(handle, fcntl.LOCK_UN)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _atomic_write(path, data):
|
|
207
|
+
# mkstemp starts private and rename publishes only a complete file.
|
|
208
|
+
fd, tmp = tempfile.mkstemp(prefix=".maco-", dir=path.parent)
|
|
209
|
+
try:
|
|
210
|
+
with os.fdopen(fd, "wb") as f:
|
|
211
|
+
f.write(data)
|
|
212
|
+
f.flush()
|
|
213
|
+
os.fsync(f.fileno())
|
|
214
|
+
os.replace(tmp, path)
|
|
215
|
+
if os.name == "posix":
|
|
216
|
+
directory_fd = os.open(path.parent, os.O_RDONLY)
|
|
217
|
+
try:
|
|
218
|
+
os.fsync(directory_fd)
|
|
219
|
+
finally:
|
|
220
|
+
os.close(directory_fd)
|
|
221
|
+
finally:
|
|
222
|
+
try:
|
|
223
|
+
os.unlink(tmp)
|
|
224
|
+
except FileNotFoundError:
|
|
225
|
+
pass
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _dpapi(data, encrypt):
|
|
229
|
+
"""Protect a Windows cache with the current user's DPAPI keys."""
|
|
230
|
+
import ctypes
|
|
231
|
+
from ctypes import wintypes
|
|
232
|
+
|
|
233
|
+
class Blob(ctypes.Structure):
|
|
234
|
+
_fields_ = [("size", wintypes.DWORD), ("data", ctypes.c_void_p)]
|
|
235
|
+
|
|
236
|
+
src = ctypes.create_string_buffer(data)
|
|
237
|
+
source = Blob(len(data), ctypes.cast(src, ctypes.c_void_p))
|
|
238
|
+
output = Blob()
|
|
239
|
+
crypt32 = ctypes.windll.crypt32
|
|
240
|
+
operation = crypt32.CryptProtectData if encrypt else crypt32.CryptUnprotectData
|
|
241
|
+
# No optional entropy or user prompt. Data can only be decrypted as this user.
|
|
242
|
+
if not operation(ctypes.byref(source), None, None, None, None, 1, ctypes.byref(output)):
|
|
243
|
+
raise MacoError("Windows could not access the protected credential cache.")
|
|
244
|
+
try:
|
|
245
|
+
return ctypes.string_at(output.data, output.size)
|
|
246
|
+
finally:
|
|
247
|
+
ctypes.windll.kernel32.LocalFree(ctypes.c_void_p(output.data))
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _read_private(path):
|
|
251
|
+
with path.open("rb") as handle:
|
|
252
|
+
if os.name != "nt":
|
|
253
|
+
st = os.fstat(handle.fileno())
|
|
254
|
+
if not stat.S_ISREG(st.st_mode) or st.st_uid != os.getuid() or st.st_mode & 0o077:
|
|
255
|
+
raise MacoError("The credential cache must be a private file owned by this user.")
|
|
256
|
+
data = handle.read()
|
|
257
|
+
return _dpapi(data, False) if os.name == "nt" else data
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _write_private(path, data):
|
|
261
|
+
_atomic_write(path, _dpapi(data, True) if os.name == "nt" else data)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _manual_accounts():
|
|
265
|
+
try:
|
|
266
|
+
data = json.loads((_directory() / "accounts.json").read_bytes())
|
|
267
|
+
if not isinstance(data, list):
|
|
268
|
+
raise ValueError()
|
|
269
|
+
profiles = [Account(**item) for item in data]
|
|
270
|
+
if (len({p.name.casefold() for p in profiles}) != len(profiles)
|
|
271
|
+
or any(p.auth == "helper" and p.agent_token_env is None for p in profiles)):
|
|
272
|
+
raise ValueError()
|
|
273
|
+
return profiles
|
|
274
|
+
except FileNotFoundError:
|
|
275
|
+
return []
|
|
276
|
+
except (ValueError, TypeError, UnicodeError):
|
|
277
|
+
raise MacoError("Invalid maco account configuration.") from None
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def list_accounts():
|
|
281
|
+
from .device_store import linked_accounts
|
|
282
|
+
profiles = _manual_accounts() + linked_accounts()
|
|
283
|
+
if len({p.name.casefold() for p in profiles}) != len(profiles):
|
|
284
|
+
raise MacoError("Duplicate names in maco account configuration.")
|
|
285
|
+
return profiles
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def public_account(account):
|
|
289
|
+
data = asdict(account)
|
|
290
|
+
if account.protocols is None:
|
|
291
|
+
del data["protocols"]
|
|
292
|
+
else:
|
|
293
|
+
data["protocols"] = list(account.protocols)
|
|
294
|
+
if account.mailbox_auth in ("gmail", "outlook"):
|
|
295
|
+
for key in ("imap_host", "smtp_host", "imap_port", "smtp_port", "smtp_security", "username"):
|
|
296
|
+
del data[key]
|
|
297
|
+
if account.auth != "helper":
|
|
298
|
+
for key in ("helper_url", "mailbox_id", "mailbox_auth", "agent_token_env"):
|
|
299
|
+
del data[key]
|
|
300
|
+
elif account.agent_token_env is None:
|
|
301
|
+
del data["agent_token_env"]
|
|
302
|
+
return data
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def add_account(account):
|
|
306
|
+
from .device_store import linked_accounts
|
|
307
|
+
if account.auth == "helper" and account.agent_token_env is None:
|
|
308
|
+
raise MacoError("Save browser-approved grants through maco account login.")
|
|
309
|
+
root = _directory()
|
|
310
|
+
with _locked(root / "accounts.lock"):
|
|
311
|
+
profiles = _manual_accounts()
|
|
312
|
+
if any(p.name.casefold() == account.name.casefold() for p in profiles + linked_accounts()):
|
|
313
|
+
raise MacoError("An account with this name already exists.")
|
|
314
|
+
if account.secret_env == _default_env(account.name, account.auth) and any(
|
|
315
|
+
p.secret_env and p.secret_env.casefold() == account.secret_env.casefold() for p in profiles
|
|
316
|
+
):
|
|
317
|
+
raise MacoError("The default credential variable overlaps another profile. Choose a distinct --secret-env.")
|
|
318
|
+
data = json.dumps([public_account(p) for p in profiles + [account]], indent=2, ensure_ascii=False)
|
|
319
|
+
_atomic_write(root / "accounts.json", (data + "\n").encode("utf-8"))
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def get_account(name=None):
|
|
323
|
+
profiles = list_accounts()
|
|
324
|
+
if not profiles:
|
|
325
|
+
raise MacoError("No account configured. Run maco account login to link your mailbox.")
|
|
326
|
+
if name is None:
|
|
327
|
+
if len(profiles) == 1:
|
|
328
|
+
return profiles[0]
|
|
329
|
+
raise MacoError("Select an account with --account.")
|
|
330
|
+
for profile in profiles:
|
|
331
|
+
if name.casefold() == profile.name.casefold():
|
|
332
|
+
return profile
|
|
333
|
+
raise MacoError("Account not found.")
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def credential(account, protocol=None):
|
|
337
|
+
if account.auth == "helper":
|
|
338
|
+
from .helper_client import lease_credential
|
|
339
|
+
return lease_credential(account, protocol)
|
|
340
|
+
if account.auth == "microsoft":
|
|
341
|
+
from .oauth import access_token
|
|
342
|
+
return access_token(account)
|
|
343
|
+
value = os.environ.get(account.secret_env, "")
|
|
344
|
+
if not value:
|
|
345
|
+
raise MacoError(f"Set the {account.secret_env} environment variable.")
|
|
346
|
+
if not all(ch.isprintable() for ch in value):
|
|
347
|
+
raise MacoError("Mail credentials must be free of control characters.")
|
|
348
|
+
return value
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def login(account, notify):
|
|
352
|
+
if account.auth == "helper":
|
|
353
|
+
raise MacoError("Managed accounts authorize each connection through Maco Mail Helper. Use auth check to verify.")
|
|
354
|
+
if account.auth != "microsoft":
|
|
355
|
+
raise MacoError(f"This profile reads its credential from {account.secret_env}.")
|
|
356
|
+
from .oauth import device_login
|
|
357
|
+
device_login(account, notify)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def logout(account):
|
|
361
|
+
if account.auth == "helper":
|
|
362
|
+
raise MacoError("Revoke this Agent's authorization in Maco Mail Helper.")
|
|
363
|
+
if account.auth != "microsoft":
|
|
364
|
+
raise MacoError(f"Unset {account.secret_env} in the calling environment.")
|
|
365
|
+
from .oauth import clear_cache
|
|
366
|
+
clear_cache(account)
|