jmapvault 0.1.0__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.
Files changed (46) hide show
  1. jmapvault/__init__.py +0 -0
  2. jmapvault/changes.py +91 -0
  3. jmapvault/cli.py +533 -0
  4. jmapvault/config.py +161 -0
  5. jmapvault/credentials.py +187 -0
  6. jmapvault/discovery.py +123 -0
  7. jmapvault/discovery_view.py +31 -0
  8. jmapvault/engine.py +297 -0
  9. jmapvault/errors.py +43 -0
  10. jmapvault/exit_codes.py +7 -0
  11. jmapvault/export/__init__.py +13 -0
  12. jmapvault/export/common.py +109 -0
  13. jmapvault/export/containers.py +77 -0
  14. jmapvault/export/mail.py +257 -0
  15. jmapvault/export/pim.py +125 -0
  16. jmapvault/export/view.py +26 -0
  17. jmapvault/ical.py +347 -0
  18. jmapvault/lock.py +32 -0
  19. jmapvault/logging_setup.py +59 -0
  20. jmapvault/meta.py +43 -0
  21. jmapvault/oauth.py +95 -0
  22. jmapvault/progress.py +176 -0
  23. jmapvault/retry.py +197 -0
  24. jmapvault/runreport.py +54 -0
  25. jmapvault/runreport_view.py +67 -0
  26. jmapvault/session.py +29 -0
  27. jmapvault/state.py +432 -0
  28. jmapvault/status_view.py +108 -0
  29. jmapvault/store.py +227 -0
  30. jmapvault/syncers/__init__.py +19 -0
  31. jmapvault/syncers/calendars.py +36 -0
  32. jmapvault/syncers/consistency.py +148 -0
  33. jmapvault/syncers/contacts.py +34 -0
  34. jmapvault/syncers/mail.py +380 -0
  35. jmapvault/syncers/objects.py +328 -0
  36. jmapvault/syncers/retire.py +39 -0
  37. jmapvault/syncers/settings.py +82 -0
  38. jmapvault/syncers/sieve.py +152 -0
  39. jmapvault/vcard.py +290 -0
  40. jmapvault/verify.py +236 -0
  41. jmapvault/verify_view.py +62 -0
  42. jmapvault-0.1.0.dist-info/METADATA +396 -0
  43. jmapvault-0.1.0.dist-info/RECORD +46 -0
  44. jmapvault-0.1.0.dist-info/WHEEL +4 -0
  45. jmapvault-0.1.0.dist-info/entry_points.txt +3 -0
  46. jmapvault-0.1.0.dist-info/licenses/LICENSE +661 -0
jmapvault/config.py ADDED
@@ -0,0 +1,161 @@
1
+ import os
2
+ import stat
3
+ import tomllib
4
+ from pathlib import Path
5
+ from typing import Annotated, Literal
6
+
7
+ import platformdirs
8
+ import tomli_w
9
+ from pydantic import (
10
+ BaseModel,
11
+ ConfigDict,
12
+ Field,
13
+ ValidationError,
14
+ field_validator,
15
+ model_validator,
16
+ )
17
+
18
+ from jmapvault.errors import ConfigError
19
+ from jmapvault.store import atomic_write_bytes
20
+
21
+ CONFIG_ENV_VAR = "JMAPVAULT_CONFIG"
22
+ APP_NAME = "jmapvault"
23
+ PRIVATE_MODE = 0o600
24
+
25
+ DataType = Literal["mail", "contacts", "calendars", "sieve", "settings"]
26
+ AuthMethod = Literal["basic", "bearer", "oauth2"]
27
+
28
+
29
+ class _Strict(BaseModel):
30
+ model_config = ConfigDict(extra="forbid")
31
+
32
+
33
+ class MailConfig(_Strict):
34
+ compress: Literal["none", "zstd"] = "none"
35
+ exports: list[str] = []
36
+
37
+ @field_validator("exports")
38
+ @classmethod
39
+ def _reject_unimplemented_exports(cls, exports: list[str]) -> list[str]:
40
+ if exports:
41
+ raise ValueError(f"mail export {exports[0]!r} is not supported yet")
42
+ return exports
43
+
44
+
45
+ class ContactsConfig(_Strict):
46
+ exports: list[Literal["vcard"]] = ["vcard"]
47
+
48
+
49
+ class CalendarsConfig(_Strict):
50
+ exports: list[Literal["ics"]] = ["ics"]
51
+
52
+
53
+ class RetriesConfig(_Strict):
54
+ max_attempts: Annotated[int, Field(ge=1)] = 5
55
+ initial_backoff_seconds: Annotated[float, Field(ge=0)] = 1.0
56
+ max_wait_seconds: Annotated[float, Field(gt=0)] = 60.0
57
+
58
+
59
+ class OAuthConfig(_Strict):
60
+ client_id: str | None = None
61
+ issuer: str | None = None
62
+ scopes: list[str] = []
63
+ flow: Literal["device", "browser"] = "device"
64
+
65
+
66
+ class ProfileConfig(_Strict):
67
+ server: str | None = None
68
+ user: str
69
+ auth: AuthMethod = "basic"
70
+ password_command: str | None = None
71
+ credential: Literal["keyring"] | None = None
72
+ destination: Path
73
+ types: list[DataType] = ["mail", "contacts", "calendars", "sieve", "settings"]
74
+ accounts: Literal["primary", "all"] | list[str] = "primary"
75
+ allow_delete: bool = False
76
+ delete_grace_days: Annotated[int, Field(ge=0)] = 30
77
+ concurrency: Annotated[int, Field(ge=1)] = 8
78
+ retries: RetriesConfig = RetriesConfig()
79
+ mail: MailConfig = MailConfig()
80
+ contacts: ContactsConfig = ContactsConfig()
81
+ calendars: CalendarsConfig = CalendarsConfig()
82
+ oauth: OAuthConfig = OAuthConfig()
83
+
84
+ @model_validator(mode="after")
85
+ def _oauth_settings_need_oauth2(self) -> "ProfileConfig":
86
+ if "oauth" in self.model_fields_set and self.auth != "oauth2":
87
+ raise ValueError('oauth settings require auth = "oauth2"')
88
+ return self
89
+
90
+
91
+ class Config(_Strict):
92
+ profiles: dict[str, ProfileConfig] = {}
93
+
94
+
95
+ def default_config_path() -> Path:
96
+ override = os.environ.get(CONFIG_ENV_VAR)
97
+ if override:
98
+ return Path(override)
99
+ return Path(platformdirs.user_config_dir(APP_NAME)) / "config.toml"
100
+
101
+
102
+ def parse_config(data: dict, source: Path) -> Config:
103
+ try:
104
+ return Config.model_validate(data)
105
+ except ValidationError as error:
106
+ raise ConfigError(_describe(error, source)) from error
107
+
108
+
109
+ def load_config(path: Path) -> Config:
110
+ try:
111
+ text = path.read_text()
112
+ except FileNotFoundError:
113
+ raise ConfigError(
114
+ f"config file {path} not found; run `jmapvault init` to create it"
115
+ ) from None
116
+ except OSError as error:
117
+ raise ConfigError(f"cannot read config file {path}: {error}") from error
118
+ try:
119
+ data = tomllib.loads(text)
120
+ except tomllib.TOMLDecodeError as error:
121
+ raise ConfigError(f"config file {path} is not valid TOML: {error}") from error
122
+ return parse_config(data, path)
123
+
124
+
125
+ def select_profile(config: Config, name: str | None) -> tuple[str, ProfileConfig]:
126
+ if name is not None:
127
+ if name not in config.profiles:
128
+ raise ConfigError(f"profile {name!r} not found; available: {_names(config) or 'none'}")
129
+ return name, config.profiles[name]
130
+ if not config.profiles:
131
+ raise ConfigError("no profiles configured; run `jmapvault init`")
132
+ if len(config.profiles) > 1:
133
+ raise ConfigError(
134
+ f"several profiles configured ({_names(config)}); choose one with --profile"
135
+ )
136
+ return next(iter(config.profiles.items()))
137
+
138
+
139
+ def _names(config: Config) -> str:
140
+ return ", ".join(sorted(config.profiles))
141
+
142
+
143
+ def _describe(error: ValidationError, source: Path) -> str:
144
+ lines = [f"invalid config in {source}:"]
145
+ for problem in error.errors():
146
+ location = ".".join(str(part) for part in problem["loc"])
147
+ lines.append(f" {location}: {problem['msg']}")
148
+ return "\n".join(lines)
149
+
150
+
151
+ def save_config(config: Config, path: Path) -> None:
152
+ profiles = {
153
+ name: profile.model_dump(mode="json", exclude_unset=True)
154
+ for name, profile in config.profiles.items()
155
+ }
156
+ data = {"profiles": profiles}
157
+ try:
158
+ mode = stat.S_IMODE(path.stat().st_mode)
159
+ except FileNotFoundError:
160
+ mode = PRIVATE_MODE
161
+ atomic_write_bytes(path, tomli_w.dumps(data).encode(), mode=mode)
@@ -0,0 +1,187 @@
1
+ import json
2
+ import os
3
+ import shlex
4
+ import subprocess
5
+ from dataclasses import dataclass
6
+
7
+ import httpx
8
+ import keyring
9
+ from jmap import JMAPError
10
+ from jmap.auth import (
11
+ BasicAuth,
12
+ BearerAuth,
13
+ OAuth2Auth,
14
+ OAuth2Token,
15
+ OAuthClient,
16
+ OAuthError,
17
+ )
18
+ from keyring.errors import KeyringError, PasswordDeleteError
19
+
20
+ from jmapvault.config import ProfileConfig
21
+ from jmapvault.errors import CredentialError
22
+
23
+ KEYRING_SERVICE = "jmapvault"
24
+ OAUTH_KEYRING_SERVICE = "jmapvault-oauth"
25
+ LOGIN_HINT = "run `jmapvault auth login`"
26
+ PASSWORD_ENV_VAR = "JMAPVAULT_PASSWORD"
27
+ TOKEN_ENV_VAR = "JMAPVAULT_TOKEN"
28
+ PASSWORD_COMMAND_TIMEOUT_SECONDS = 60
29
+
30
+
31
+ def resolve_secret(profile: ProfileConfig) -> str:
32
+ env_var = TOKEN_ENV_VAR if profile.auth == "bearer" else PASSWORD_ENV_VAR
33
+ secret = os.environ.get(env_var)
34
+ if secret:
35
+ return secret
36
+ if profile.password_command:
37
+ return _run_password_command(profile.password_command)
38
+ secret = _read_keyring(profile.user)
39
+ if secret:
40
+ return secret
41
+ raise CredentialError(
42
+ f"no credential found for {profile.user}: set {env_var}, configure "
43
+ "password_command, or run `jmapvault init --store-in-keyring`"
44
+ )
45
+
46
+
47
+ def store_secret(profile: ProfileConfig, secret: str) -> None:
48
+ try:
49
+ keyring.set_password(KEYRING_SERVICE, profile.user, secret)
50
+ except KeyringError as error:
51
+ raise CredentialError(f"cannot store the secret in the keyring: {error}") from error
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class StoredGrant:
56
+ client_id: str
57
+ issuer: str
58
+ token: OAuth2Token
59
+
60
+
61
+ class KeyringTokenStore:
62
+ def __init__(self, user: str) -> None:
63
+ self._user = user
64
+
65
+ def load(self) -> StoredGrant | None:
66
+ try:
67
+ raw = keyring.get_password(OAUTH_KEYRING_SERVICE, self._user)
68
+ except KeyringError as error:
69
+ raise CredentialError(
70
+ f"cannot read the OAuth token from the keyring: {error}"
71
+ ) from error
72
+ if raw is None:
73
+ return None
74
+ try:
75
+ record = json.loads(raw)
76
+ return StoredGrant(
77
+ client_id=record["client_id"],
78
+ issuer=record["issuer"],
79
+ token=OAuth2Token(**record["token"]),
80
+ )
81
+ except (ValueError, KeyError, TypeError) as error:
82
+ raise CredentialError(
83
+ f"the stored OAuth token for {self._user} is unreadable; {LOGIN_HINT}"
84
+ ) from error
85
+
86
+ def write(self, grant: StoredGrant) -> None:
87
+ token = grant.token
88
+ record = {
89
+ "client_id": grant.client_id,
90
+ "issuer": grant.issuer,
91
+ "token": {
92
+ "access_token": token.access_token,
93
+ "refresh_token": token.refresh_token,
94
+ "expires_at": token.expires_at,
95
+ "scope": token.scope,
96
+ },
97
+ }
98
+ try:
99
+ keyring.set_password(OAUTH_KEYRING_SERVICE, self._user, json.dumps(record))
100
+ except KeyringError as error:
101
+ raise CredentialError(
102
+ f"cannot store the OAuth token in the keyring: {error}"
103
+ ) from error
104
+
105
+ def save(self, token: OAuth2Token) -> None:
106
+ grant = self.load()
107
+ if grant is None:
108
+ raise CredentialError(f"no stored OAuth grant for {self._user}; {LOGIN_HINT}")
109
+ self.write(StoredGrant(grant.client_id, grant.issuer, token))
110
+
111
+ def delete(self) -> bool:
112
+ if self.load() is None:
113
+ return False
114
+ try:
115
+ keyring.delete_password(OAUTH_KEYRING_SERVICE, self._user)
116
+ except PasswordDeleteError:
117
+ return False
118
+ except KeyringError as error:
119
+ raise CredentialError(f"cannot delete the OAuth token: {error}") from error
120
+ return True
121
+
122
+
123
+ def _build_oauth2_auth(profile: ProfileConfig) -> OAuth2Auth:
124
+ store = KeyringTokenStore(profile.user)
125
+ grant = store.load()
126
+ if grant is None:
127
+ raise CredentialError(f"no OAuth token stored for {profile.user}; {LOGIN_HINT}")
128
+ return OAuth2Auth(grant.token, refresh=_refresher(grant), store=store)
129
+
130
+
131
+ def _refresher(grant: StoredGrant):
132
+ def refresh(token: OAuth2Token) -> OAuth2Token:
133
+ if token.refresh_token is None:
134
+ raise CredentialError(f"the stored OAuth token cannot be refreshed; {LOGIN_HINT}")
135
+ try:
136
+ metadata = OAuthClient.discover_from_issuer(grant.issuer)
137
+ with OAuthClient(metadata, client_id=grant.client_id) as client:
138
+ return client.refresh(token.refresh_token)
139
+ except OAuthError as error:
140
+ raise CredentialError(
141
+ f"the OAuth token was refused ({error.error}); {LOGIN_HINT}"
142
+ ) from error
143
+ except JMAPError as error:
144
+ raise CredentialError(f"cannot refresh the OAuth token: {error}") from error
145
+
146
+ return refresh
147
+
148
+
149
+ def build_auth(profile: ProfileConfig) -> httpx.Auth:
150
+ if profile.auth == "oauth2":
151
+ return _build_oauth2_auth(profile)
152
+ secret = resolve_secret(profile)
153
+ if profile.auth == "bearer":
154
+ return BearerAuth(secret)
155
+ return BasicAuth(profile.user, secret)
156
+
157
+
158
+ def _run_password_command(command: str) -> str:
159
+ try:
160
+ completed = subprocess.run(
161
+ shlex.split(command),
162
+ capture_output=True,
163
+ text=True,
164
+ check=False,
165
+ timeout=PASSWORD_COMMAND_TIMEOUT_SECONDS,
166
+ )
167
+ except (OSError, ValueError, subprocess.TimeoutExpired) as error:
168
+ raise CredentialError(f"password_command could not run: {_reason(error)}") from error
169
+ if completed.returncode != 0:
170
+ raise CredentialError(f"password_command exited with status {completed.returncode}")
171
+ secret = completed.stdout.rstrip("\r\n")
172
+ if not secret:
173
+ raise CredentialError("password_command produced empty output")
174
+ return secret
175
+
176
+
177
+ def _reason(error: Exception) -> str:
178
+ if isinstance(error, subprocess.TimeoutExpired):
179
+ return f"timed out after {PASSWORD_COMMAND_TIMEOUT_SECONDS}s"
180
+ return str(error)
181
+
182
+
183
+ def _read_keyring(user: str) -> str | None:
184
+ try:
185
+ return keyring.get_password(KEYRING_SERVICE, user)
186
+ except KeyringError:
187
+ return None
jmapvault/discovery.py ADDED
@@ -0,0 +1,123 @@
1
+ from enum import StrEnum
2
+ from typing import Any, get_args
3
+
4
+ from jmap.core.session import CORE_URN, Session
5
+ from pydantic import BaseModel
6
+
7
+ from jmapvault.config import DataType
8
+
9
+ JMAP = "urn:ietf:params:jmap:"
10
+
11
+ SUPPORTED_TYPES: dict[DataType, tuple[str, ...]] = {
12
+ "mail": (f"{JMAP}mail",),
13
+ "contacts": (f"{JMAP}contacts",),
14
+ "calendars": (f"{JMAP}calendars",),
15
+ "sieve": (f"{JMAP}sieve",),
16
+ "settings": (f"{JMAP}submission", f"{JMAP}vacationresponse"),
17
+ }
18
+
19
+ assert set(SUPPORTED_TYPES) == set(get_args(DataType))
20
+
21
+
22
+ class CapabilityStatus(StrEnum):
23
+ SUPPORTED = "supported"
24
+ SUPPORTED_BETA = "supported-beta"
25
+ INFORMATIONAL = "informational"
26
+ NOT_APPLICABLE = "not-applicable"
27
+ NOT_SUPPORTED = "not-supported"
28
+
29
+
30
+ BETA_URNS = frozenset({f"{JMAP}calendars"})
31
+ INFORMATIONAL_URNS = frozenset({f"{JMAP}quota"})
32
+ NOT_APPLICABLE_URNS = frozenset(
33
+ {
34
+ CORE_URN,
35
+ f"{JMAP}websocket",
36
+ f"{JMAP}principals",
37
+ f"{JMAP}principals:owner",
38
+ f"{JMAP}blob",
39
+ }
40
+ )
41
+
42
+
43
+ def data_type_for(urn: str) -> DataType | None:
44
+ for data_type, urns in SUPPORTED_TYPES.items():
45
+ if urn in urns:
46
+ return data_type
47
+ return None
48
+
49
+
50
+ def status_for(urn: str) -> CapabilityStatus:
51
+ if urn in BETA_URNS:
52
+ return CapabilityStatus.SUPPORTED_BETA
53
+ if data_type_for(urn):
54
+ return CapabilityStatus.SUPPORTED
55
+ if urn in INFORMATIONAL_URNS:
56
+ return CapabilityStatus.INFORMATIONAL
57
+ if urn in NOT_APPLICABLE_URNS:
58
+ return CapabilityStatus.NOT_APPLICABLE
59
+ return CapabilityStatus.NOT_SUPPORTED
60
+
61
+
62
+ class CapabilityReport(BaseModel):
63
+ urn: str
64
+ status: CapabilityStatus
65
+ data_type: DataType | None
66
+
67
+
68
+ class AccountReport(BaseModel):
69
+ id: str
70
+ name: str
71
+ is_personal: bool
72
+ is_read_only: bool
73
+ capabilities: list[str]
74
+
75
+
76
+ class LimitsReport(BaseModel):
77
+ max_objects_in_get: int
78
+ max_concurrent_requests: int
79
+ max_calls_in_request: int
80
+ max_size_upload: int
81
+ max_size_download: int | None
82
+
83
+
84
+ class DiscoveryReport(BaseModel):
85
+ username: str
86
+ capabilities: list[CapabilityReport]
87
+ accounts: list[AccountReport]
88
+ limits: LimitsReport
89
+
90
+
91
+ def _optional_int(value: Any) -> int | None:
92
+ if isinstance(value, int) and not isinstance(value, bool):
93
+ return value
94
+ return None
95
+
96
+
97
+ def discover_session(session: Session) -> DiscoveryReport:
98
+ limits = session.limits
99
+ core: Any = session.capabilities.get(CORE_URN) or {}
100
+ return DiscoveryReport(
101
+ username=session.username,
102
+ capabilities=[
103
+ CapabilityReport(urn=urn, status=status_for(urn), data_type=data_type_for(urn))
104
+ for urn in session.capabilities
105
+ ],
106
+ accounts=[
107
+ AccountReport(
108
+ id=str(account.id),
109
+ name=account.name,
110
+ is_personal=account.is_personal,
111
+ is_read_only=account.is_read_only,
112
+ capabilities=list(account.account_capabilities),
113
+ )
114
+ for account in session.accounts.values()
115
+ ],
116
+ limits=LimitsReport(
117
+ max_objects_in_get=limits.max_objects_in_get,
118
+ max_concurrent_requests=limits.max_concurrent_requests,
119
+ max_calls_in_request=limits.max_calls_in_request,
120
+ max_size_upload=limits.max_size_upload,
121
+ max_size_download=_optional_int(core.get("maxSizeDownload")),
122
+ ),
123
+ )
@@ -0,0 +1,31 @@
1
+ from rich.console import Console
2
+ from rich.table import Table
3
+
4
+ from jmapvault.discovery import DiscoveryReport
5
+
6
+
7
+ def render_report(report: DiscoveryReport, console: Console) -> None:
8
+ capabilities = Table("Capability", "Status", "Data type", title="Capabilities")
9
+ for capability in report.capabilities:
10
+ capabilities.add_row(capability.urn, capability.status.value, capability.data_type or "-")
11
+
12
+ accounts = Table("Id", "Name", "Kind", "Access", "Capabilities", title="Accounts")
13
+ for account in report.accounts:
14
+ accounts.add_row(
15
+ account.id,
16
+ account.name,
17
+ "personal" if account.is_personal else "shared",
18
+ "read-only" if account.is_read_only else "read-write",
19
+ "\n".join(account.capabilities),
20
+ )
21
+
22
+ limits = Table("Limit", "Value", title="Limits")
23
+ limits.add_row("maxObjectsInGet", str(report.limits.max_objects_in_get))
24
+ limits.add_row("maxConcurrentRequests", str(report.limits.max_concurrent_requests))
25
+ limits.add_row("maxCallsInRequest", str(report.limits.max_calls_in_request))
26
+ limits.add_row("maxSizeUpload", str(report.limits.max_size_upload))
27
+ if report.limits.max_size_download is not None:
28
+ limits.add_row("maxSizeDownload", str(report.limits.max_size_download))
29
+
30
+ for table in (capabilities, accounts, limits):
31
+ console.print(table)