gws-cli 1.0.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.
gws/config.py ADDED
@@ -0,0 +1,451 @@
1
+ """Configuration management for GWS CLI."""
2
+
3
+ import copy
4
+ import json
5
+ import os
6
+ import re
7
+ import shutil
8
+ from dataclasses import dataclass, field, asdict, fields
9
+ from pathlib import Path
10
+ from typing import Any, ClassVar
11
+
12
+ def _write_secure_file(path: Path, content: str) -> None:
13
+ """Write content to path with 0o600 permissions (owner read/write only)."""
14
+ path.parent.mkdir(parents=True, exist_ok=True)
15
+ fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
16
+ with os.fdopen(fd, "w") as f:
17
+ f.write(content)
18
+
19
+
20
+ # Account names must be alphanumeric, hyphens, or underscores
21
+ _VALID_ACCOUNT_NAME = re.compile(r"^[a-zA-Z0-9_-]+$")
22
+
23
+
24
+ @dataclass
25
+ class AccountEntry:
26
+ """Metadata for a named account."""
27
+
28
+ name: str = ""
29
+ email: str = ""
30
+ created_at: str = ""
31
+
32
+
33
+ @dataclass
34
+ class AccountsRegistry:
35
+ """Registry of all named accounts."""
36
+
37
+ default_account: str = ""
38
+ entries: dict[str, AccountEntry] = field(default_factory=dict)
39
+
40
+
41
+ @dataclass
42
+ class Config:
43
+ """CLI configuration with enabled services and security settings."""
44
+
45
+ BASE_DIR: ClassVar[Path] = Path.home() / ".config" / "gws-cli"
46
+ CONFIG_PATH: ClassVar[Path] = BASE_DIR / "gws_config.json"
47
+ _LEGACY_BASE_DIR: ClassVar[Path] = Path.home() / ".claude" / ".google-workspace"
48
+
49
+ ALL_SERVICES: ClassVar[list[str]] = [
50
+ "docs",
51
+ "sheets",
52
+ "slides",
53
+ "drive",
54
+ "gmail",
55
+ "calendar",
56
+ "contacts",
57
+ "convert",
58
+ ]
59
+
60
+ DEFAULT_KROKI_URL: ClassVar[str] = "https://kroki.io"
61
+
62
+ # Read-only operations per service (used by `account set-readonly`)
63
+ READ_ONLY_OPS: ClassVar[dict[str, list[str]]] = {
64
+ "gmail": [
65
+ "list", "read", "search", "labels", "drafts", "get-draft",
66
+ "list-attachments", "download-attachment", "threads", "get-thread",
67
+ "get-vacation", "get-signature", "filters", "get-filter",
68
+ "get-label", "history",
69
+ ],
70
+ "docs": [
71
+ "list-tabs", "read", "structure", "list-tables",
72
+ "list-headers-footers", "find-text", "list-named-ranges",
73
+ "list-footnotes", "suggestions", "get-page-format", "document-mode",
74
+ "export",
75
+ ],
76
+ "sheets": [
77
+ "metadata", "read", "batch-get", "list-filter-views",
78
+ "list-pivot-tables", "list-protected-ranges", "list-named-ranges",
79
+ ],
80
+ "slides": ["metadata", "read", "get-speaker-notes"],
81
+ "drive": [
82
+ "list", "search", "get", "download", "export", "list-comments",
83
+ "list-revisions", "get-revision", "list-trash", "list-permissions",
84
+ "get-permission", "list-replies", "get-reply", "changes-token",
85
+ "list-changes", "list-shared-drives", "get-shared-drive", "generate-ids",
86
+ ],
87
+ "calendar": [
88
+ "calendars", "list", "get", "instances", "attendees", "freebusy",
89
+ "list-acl", "get-reminders", "get-default-reminders", "colors",
90
+ ],
91
+ "contacts": [
92
+ "list", "get", "groups", "get-group", "get-photo",
93
+ "search-directory", "list-directory", "batch-get",
94
+ ],
95
+ "convert": [],
96
+ }
97
+
98
+ enabled_services: list[str] = field(default_factory=lambda: Config.ALL_SERVICES.copy())
99
+ kroki_url: str = field(default_factory=lambda: Config.DEFAULT_KROKI_URL)
100
+ security_enabled: bool = True # Prompt injection protection enabled by default
101
+
102
+ # Service-specific security settings
103
+ allowlisted_documents: list[str] = field(default_factory=list) # Docs/Sheets/Slides IDs
104
+ allowlisted_emails: list[str] = field(default_factory=list) # Gmail message IDs
105
+ disabled_security_services: list[str] = field(default_factory=list) # Services to skip
106
+ disabled_security_operations: dict[str, bool] = field(default_factory=dict) # e.g., {"gmail.send": True}
107
+
108
+ # Auth mode: "local" uses client_secret.json, "server" delegates to oauth-token-relay
109
+ mode: str = "local"
110
+ server_url: str | None = None
111
+ server_provider: str | None = None
112
+
113
+ # Encryption salt for secret files (auto-generated on first use)
114
+ encryption_salt: str = ""
115
+
116
+ # Read-only OAuth scopes (requests .readonly scopes instead of full access)
117
+ read_only: bool = False
118
+
119
+ # Multi-account support (None = legacy single-account mode)
120
+ accounts: AccountsRegistry | None = None
121
+
122
+ @classmethod
123
+ def _migrate_config_dir(cls) -> None:
124
+ """Migrate config from old ~/.claude/.google-workspace/ to new location."""
125
+ if cls._LEGACY_BASE_DIR.exists() and not cls.BASE_DIR.exists():
126
+ import sys
127
+
128
+ try:
129
+ shutil.copytree(cls._LEGACY_BASE_DIR, cls.BASE_DIR)
130
+ print(
131
+ f"[gws-cli] Migrated config from {cls._LEGACY_BASE_DIR} to {cls.BASE_DIR}",
132
+ file=sys.stderr,
133
+ )
134
+ except OSError as e:
135
+ print(f"[gws-cli] Warning: failed to migrate config: {e}", file=sys.stderr)
136
+
137
+ @classmethod
138
+ def load(cls) -> "Config":
139
+ """Load configuration from file or create default."""
140
+ cls._migrate_config_dir()
141
+ if cls.CONFIG_PATH.exists():
142
+ try:
143
+ with open(cls.CONFIG_PATH) as f:
144
+ data = json.load(f)
145
+ return cls._from_dict(data)
146
+ except (json.JSONDecodeError, TypeError) as e:
147
+ import sys
148
+ print(f"[gws-cli] Warning: corrupt config file, using defaults: {e}", file=sys.stderr)
149
+ return cls()
150
+ return cls()
151
+
152
+ @classmethod
153
+ def _from_dict(cls, data: dict[str, Any]) -> "Config":
154
+ """Deserialize config from dict, handling nested accounts structure."""
155
+ accounts_data = data.pop("accounts", None)
156
+ # Filter to known fields to avoid TypeError on future/unknown keys
157
+ known_fields = {f.name for f in fields(cls)}
158
+ filtered = {k: v for k, v in data.items() if k in known_fields}
159
+ config = cls(**filtered)
160
+
161
+ if accounts_data is not None:
162
+ entries = {}
163
+ for name, entry_data in accounts_data.get("entries", {}).items():
164
+ entries[name] = AccountEntry(**entry_data)
165
+ config.accounts = AccountsRegistry(
166
+ default_account=accounts_data.get("default_account", ""),
167
+ entries=entries,
168
+ )
169
+
170
+ return config
171
+
172
+ def save(self) -> None:
173
+ """Save configuration to file."""
174
+ self.CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
175
+ data = asdict(self)
176
+ # Omit defaults for clean JSON
177
+ if self.accounts is None:
178
+ data.pop("accounts", None)
179
+ if self.server_url is None:
180
+ data.pop("server_url", None)
181
+ if self.server_provider is None:
182
+ data.pop("server_provider", None)
183
+ if self.mode == "local":
184
+ data.pop("mode", None)
185
+ if not self.read_only:
186
+ data.pop("read_only", None)
187
+ _write_secure_file(self.CONFIG_PATH, json.dumps(data, indent=2))
188
+
189
+ _encryption_key_cache: bytes | None = None
190
+ _encryption_key_resolved: bool = False
191
+
192
+ def get_encryption_key(self) -> bytes | None:
193
+ """Return the Fernet encryption key, or None if encryption is disabled.
194
+
195
+ The key is derived at runtime from the machine ID, current username,
196
+ and a random salt stored in the config file. Set GWS_ENCRYPTION=none
197
+ to disable encryption entirely.
198
+ """
199
+ if self._encryption_key_resolved:
200
+ return self._encryption_key_cache
201
+
202
+ from gws.crypto import derive_key, generate_salt
203
+
204
+ if os.environ.get("GWS_ENCRYPTION", "").lower() == "none":
205
+ self._encryption_key_cache = None
206
+ self._encryption_key_resolved = True
207
+ return None
208
+
209
+ if not self.encryption_salt:
210
+ self.encryption_salt = generate_salt()
211
+ self.save()
212
+
213
+ self._encryption_key_cache = derive_key(self.encryption_salt, "gws-cli")
214
+ self._encryption_key_resolved = True
215
+ return self._encryption_key_cache
216
+
217
+ def is_service_enabled(self, service: str) -> bool:
218
+ """Check if a service is enabled."""
219
+ return service in self.enabled_services
220
+
221
+ def enable_service(self, service: str) -> bool:
222
+ """Enable a service. Returns True if changed."""
223
+ if service in self.ALL_SERVICES and service not in self.enabled_services:
224
+ self.enabled_services.append(service)
225
+ self.save()
226
+ return True
227
+ return False
228
+
229
+ def disable_service(self, service: str) -> bool:
230
+ """Disable a service. Returns True if changed."""
231
+ if service in self.enabled_services:
232
+ self.enabled_services.remove(service)
233
+ self.save()
234
+ return True
235
+ return False
236
+
237
+ def is_allowlisted(self, source_type: str, source_id: str) -> bool:
238
+ """Check if a source is in the allowlist."""
239
+ if source_type in ("email", "message"):
240
+ return source_id in self.allowlisted_emails
241
+ elif source_type in ("document", "docs", "spreadsheet", "sheets", "slides"):
242
+ return source_id in self.allowlisted_documents
243
+ return False
244
+
245
+ def is_security_enabled_for_operation(self, operation: str) -> bool:
246
+ """Check if security is enabled for an operation (e.g., 'gmail.read')."""
247
+ if not self.security_enabled:
248
+ return False
249
+ # Check if explicitly disabled
250
+ if operation in self.disabled_security_operations:
251
+ return not self.disabled_security_operations[operation]
252
+ # Check if service is disabled
253
+ service = operation.split(".")[0] if "." in operation else operation
254
+ return service not in self.disabled_security_services
255
+
256
+ # ── Multi-account methods ──────────────────────────────────────────
257
+
258
+ @property
259
+ def is_multi_account(self) -> bool:
260
+ """Check if multi-account mode is active."""
261
+ return self.accounts is not None and len(self.accounts.entries) > 0
262
+
263
+ @staticmethod
264
+ def validate_account_name(name: str) -> None:
265
+ """Validate account name is safe for filesystem use."""
266
+ if not _VALID_ACCOUNT_NAME.match(name):
267
+ raise ValueError(
268
+ f"Invalid account name '{name}'. "
269
+ "Use only letters, numbers, hyphens, and underscores."
270
+ )
271
+
272
+ def get_account_dir(self, name: str) -> Path:
273
+ """Get the directory for a named account."""
274
+ self.validate_account_name(name)
275
+ return self.BASE_DIR / "accounts" / name
276
+
277
+ def resolve_account(self, account: str | None = None) -> str | None:
278
+ """Resolve which account to use.
279
+
280
+ Priority: explicit arg > GWS_ACCOUNT env > default > None (legacy).
281
+ Validates the resolved name to prevent path traversal.
282
+ """
283
+ from gws.exceptions import AuthError
284
+
285
+ resolved: str | None = None
286
+ if account:
287
+ resolved = account
288
+ elif (env_account := os.environ.get("GWS_ACCOUNT")):
289
+ resolved = env_account
290
+ elif self.accounts and self.accounts.default_account:
291
+ resolved = self.accounts.default_account
292
+
293
+ if resolved is not None:
294
+ try:
295
+ self.validate_account_name(resolved)
296
+ except ValueError as e:
297
+ raise AuthError(str(e)) from e
298
+ return resolved
299
+
300
+ def load_effective_config(self, account: str | None) -> "Config":
301
+ """Return a config with per-account overrides applied.
302
+
303
+ Deep-copies self, then overlays fields from per-account config.json.
304
+ """
305
+ if not account:
306
+ return self
307
+ overrides = self.load_account_config(account)
308
+ if not overrides:
309
+ return self
310
+ effective = copy.deepcopy(self)
311
+ # Overlay supported fields
312
+ if "enabled_services" in overrides:
313
+ effective.enabled_services = overrides["enabled_services"]
314
+ if "kroki_url" in overrides:
315
+ effective.kroki_url = overrides["kroki_url"]
316
+ if "security_enabled" in overrides:
317
+ effective.security_enabled = overrides["security_enabled"]
318
+ if "disabled_security_services" in overrides:
319
+ effective.disabled_security_services = overrides["disabled_security_services"]
320
+ if "disabled_security_operations" in overrides:
321
+ effective.disabled_security_operations = overrides["disabled_security_operations"]
322
+ if "server_provider" in overrides:
323
+ effective.server_provider = overrides["server_provider"]
324
+ if "mode" in overrides:
325
+ effective.mode = overrides["mode"]
326
+ if "server_url" in overrides:
327
+ effective.server_url = overrides["server_url"]
328
+ if "read_only" in overrides:
329
+ effective.read_only = overrides["read_only"]
330
+ return effective
331
+
332
+ def add_account(self, name: str, display_name: str = "", email: str = "") -> None:
333
+ """Register a new named account."""
334
+ from datetime import datetime, timezone
335
+
336
+ if self.accounts is None:
337
+ self.accounts = AccountsRegistry()
338
+
339
+ self.accounts.entries[name] = AccountEntry(
340
+ name=display_name,
341
+ email=email,
342
+ created_at=datetime.now(timezone.utc).isoformat(),
343
+ )
344
+
345
+ # First account becomes default
346
+ if not self.accounts.default_account:
347
+ self.accounts.default_account = name
348
+
349
+ # Create account directory
350
+ account_dir = self.get_account_dir(name)
351
+ account_dir.mkdir(parents=True, exist_ok=True)
352
+
353
+ self.save()
354
+
355
+ def remove_account(self, name: str) -> bool:
356
+ """Remove a named account and its files. Returns True if removed."""
357
+ if not self.accounts or name not in self.accounts.entries:
358
+ return False
359
+
360
+ del self.accounts.entries[name]
361
+
362
+ # Clean up account directory
363
+ account_dir = self.get_account_dir(name)
364
+ if account_dir.exists():
365
+ shutil.rmtree(account_dir)
366
+
367
+ # Reassign default if needed
368
+ if self.accounts.default_account == name:
369
+ if self.accounts.entries:
370
+ self.accounts.default_account = next(iter(self.accounts.entries))
371
+ else:
372
+ self.accounts.default_account = ""
373
+
374
+ # Revert to legacy mode if no accounts left
375
+ if not self.accounts.entries:
376
+ self.accounts = None
377
+
378
+ self.save()
379
+ return True
380
+
381
+ def set_default_account(self, name: str) -> bool:
382
+ """Set the default account. Returns True if changed."""
383
+ if not self.accounts or name not in self.accounts.entries:
384
+ return False
385
+ self.accounts.default_account = name
386
+ self.save()
387
+ return True
388
+
389
+ def list_accounts(self) -> dict[str, Any]:
390
+ """Return all accounts with metadata and default flag."""
391
+ if not self.accounts:
392
+ return {}
393
+ result = {}
394
+ for name, entry in self.accounts.entries.items():
395
+ result[name] = {
396
+ "name": entry.name,
397
+ "email": entry.email,
398
+ "created_at": entry.created_at,
399
+ "is_default": name == self.accounts.default_account,
400
+ }
401
+ return result
402
+
403
+ def get_account_display_name(self, account: str | None) -> str:
404
+ """Get the display name for an account, or empty string."""
405
+ if not account or not self.accounts:
406
+ return ""
407
+ entry = self.accounts.entries.get(account)
408
+ return entry.name if entry else ""
409
+
410
+ def update_account(self, account: str, display_name: str | None = None, email: str | None = None) -> bool:
411
+ """Update account metadata fields. Returns True if changed."""
412
+ if not self.accounts or account not in self.accounts.entries:
413
+ return False
414
+ entry = self.accounts.entries[account]
415
+ changed = False
416
+ if display_name is not None:
417
+ entry.name = display_name
418
+ changed = True
419
+ if email is not None:
420
+ entry.email = email
421
+ changed = True
422
+ if changed:
423
+ self.save()
424
+ return changed
425
+
426
+ def save_account_config(self, name: str, overrides: dict[str, Any]) -> None:
427
+ """Save per-account config overrides."""
428
+ account_dir = self.get_account_dir(name)
429
+ account_dir.mkdir(parents=True, exist_ok=True)
430
+ config_path = account_dir / "config.json"
431
+ _write_secure_file(config_path, json.dumps(overrides, indent=2))
432
+
433
+ def load_account_config(self, name: str) -> dict[str, Any]:
434
+ """Load per-account config overrides."""
435
+ config_path = self.get_account_dir(name) / "config.json"
436
+ if config_path.exists():
437
+ try:
438
+ with open(config_path) as f:
439
+ data: dict[str, Any] = json.load(f)
440
+ return data
441
+ except (json.JSONDecodeError, TypeError) as e:
442
+ import sys
443
+ print(f"[gws-cli] Warning: corrupt account config for '{name}', ignoring: {e}", file=sys.stderr)
444
+ return {}
445
+ return {}
446
+
447
+ def clear_account_config(self, name: str) -> None:
448
+ """Remove per-account config (full inheritance from global)."""
449
+ config_path = self.get_account_dir(name) / "config.json"
450
+ if config_path.exists():
451
+ config_path.unlink()
gws/context.py ADDED
@@ -0,0 +1,14 @@
1
+ """Runtime context for the active account."""
2
+
3
+ _active_account: str | None = None
4
+
5
+
6
+ def get_active_account() -> str | None:
7
+ """Get the currently active account name."""
8
+ return _active_account
9
+
10
+
11
+ def set_active_account(account: str | None) -> None:
12
+ """Set the active account name for this invocation."""
13
+ global _active_account
14
+ _active_account = account
gws/crypto.py ADDED
@@ -0,0 +1,217 @@
1
+ """Encryption at rest for secret files (tokens, credentials, API keys).
2
+
3
+ Derives a Fernet key at runtime from machine-specific identifiers so the key
4
+ is never stored on disk. An attacker who exfiltrates encrypted files to
5
+ another machine (or another user account) cannot decrypt them.
6
+
7
+ Two modes:
8
+ - auto (default): key derived from machine_id + username + salt via HKDF
9
+ - none (opt-out via env var): no encryption, plaintext JSON
10
+ """
11
+
12
+ import base64
13
+ import getpass
14
+ import json
15
+ import os
16
+ import platform
17
+ import secrets as secrets_mod
18
+ import subprocess
19
+ import sys
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from cryptography.fernet import Fernet, InvalidToken
24
+ from cryptography.hazmat.primitives.hashes import SHA256
25
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
26
+
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Machine fingerprint (cross-platform)
30
+ # ---------------------------------------------------------------------------
31
+
32
+ def _get_machine_id_linux() -> str:
33
+ try:
34
+ return Path("/etc/machine-id").read_text().strip()
35
+ except (OSError, FileNotFoundError):
36
+ return ""
37
+
38
+
39
+ def _get_machine_id_macos() -> str:
40
+ try:
41
+ result = subprocess.run(
42
+ ["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"],
43
+ capture_output=True, text=True, timeout=5,
44
+ )
45
+ for line in result.stdout.splitlines():
46
+ if "IOPlatformUUID" in line:
47
+ # Line format: "IOPlatformUUID" = "XXXXXXXX-XXXX-..."
48
+ parts = line.split('"')
49
+ if len(parts) >= 4:
50
+ return parts[-2]
51
+ except (OSError, subprocess.TimeoutExpired):
52
+ pass
53
+ return ""
54
+
55
+
56
+ def _get_machine_id_windows() -> str:
57
+ try:
58
+ import winreg
59
+ key = winreg.OpenKey(
60
+ winreg.HKEY_LOCAL_MACHINE,
61
+ r"SOFTWARE\Microsoft\Cryptography",
62
+ )
63
+ value, _ = winreg.QueryValueEx(key, "MachineGuid")
64
+ winreg.CloseKey(key)
65
+ return str(value)
66
+ except (OSError, ImportError):
67
+ return ""
68
+
69
+
70
+ def get_machine_id() -> str:
71
+ """Get a stable, per-installation machine identifier."""
72
+ system = platform.system()
73
+ if system == "Linux":
74
+ return _get_machine_id_linux()
75
+ elif system == "Darwin":
76
+ return _get_machine_id_macos()
77
+ elif system == "Windows":
78
+ return _get_machine_id_windows()
79
+ return ""
80
+
81
+
82
+ # ---------------------------------------------------------------------------
83
+ # Key derivation
84
+ # ---------------------------------------------------------------------------
85
+
86
+ def generate_salt() -> str:
87
+ """Generate a random 64-char hex salt for key derivation."""
88
+ return secrets_mod.token_hex(32)
89
+
90
+
91
+ def derive_key(salt: str, app_id: str) -> bytes:
92
+ """Derive a Fernet key from machine fingerprint + username + salt.
93
+
94
+ Args:
95
+ salt: Random salt stored in the (plaintext) config file.
96
+ app_id: Application identifier (e.g. "gws-cli" or "zd-cli").
97
+
98
+ Returns:
99
+ URL-safe base64-encoded 32-byte key suitable for Fernet.
100
+
101
+ Raises:
102
+ RuntimeError: If the machine ID cannot be determined.
103
+ """
104
+ machine_id = get_machine_id()
105
+ if not machine_id:
106
+ raise RuntimeError(
107
+ "Cannot derive encryption key: machine ID not available. "
108
+ "Set the appropriate *_ENCRYPTION=none env var to disable encryption."
109
+ )
110
+
111
+ username = getpass.getuser()
112
+ fingerprint = f"{machine_id}:{username}:{app_id}".encode()
113
+
114
+ hkdf = HKDF(
115
+ algorithm=SHA256(),
116
+ length=32,
117
+ salt=salt.encode(),
118
+ info=b"token-encryption",
119
+ )
120
+ key_bytes = hkdf.derive(fingerprint)
121
+ return base64.urlsafe_b64encode(key_bytes)
122
+
123
+
124
+ # ---------------------------------------------------------------------------
125
+ # Encrypt / decrypt helpers
126
+ # ---------------------------------------------------------------------------
127
+
128
+ def _enc_path(path: Path) -> Path:
129
+ """Return the .enc sibling of a path: token.json → token.json.enc."""
130
+ return path.parent / (path.name + ".enc")
131
+
132
+
133
+ def save_encrypted(path: Path, data: dict[str, Any], key: bytes | None) -> None:
134
+ """Save *data* as JSON — encrypted if *key* is provided, plaintext otherwise.
135
+
136
+ Encrypted files are written with the ``.enc`` suffix appended to *path*.
137
+ If a plaintext version of the file exists when saving encrypted, it is
138
+ removed (migration cleanup). Files are created with 0o600 permissions.
139
+ """
140
+ path.parent.mkdir(parents=True, exist_ok=True)
141
+
142
+ if key is not None:
143
+ dest = _enc_path(path)
144
+ fernet = Fernet(key)
145
+ ciphertext = fernet.encrypt(json.dumps(data, indent=2).encode())
146
+ fd = os.open(str(dest), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
147
+ with os.fdopen(fd, "wb") as f:
148
+ f.write(ciphertext)
149
+ # Remove plaintext leftover from before encryption was enabled
150
+ if path.exists():
151
+ path.unlink()
152
+ else:
153
+ fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
154
+ with os.fdopen(fd, "w") as f:
155
+ json.dump(data, f, indent=2)
156
+
157
+
158
+ def load_encrypted(path: Path, key: bytes | None) -> dict[str, Any] | None:
159
+ """Load a JSON dict, handling both encrypted and plaintext files.
160
+
161
+ When *key* is provided:
162
+ 1. Try ``path.enc`` first — decrypt and return.
163
+ 2. Fall back to plaintext *path* — auto-migrate (encrypt in place) and return.
164
+ 3. If decryption fails (key changed / wrong machine): return ``None``.
165
+
166
+ When *key* is ``None``: read plaintext *path* only.
167
+
168
+ Returns ``None`` if the file does not exist or cannot be read.
169
+ """
170
+ enc = _enc_path(path)
171
+
172
+ if key is not None:
173
+ # Prefer encrypted file
174
+ if enc.exists():
175
+ try:
176
+ ciphertext = enc.read_bytes()
177
+ plaintext = Fernet(key).decrypt(ciphertext)
178
+ return json.loads(plaintext)
179
+ except (InvalidToken, json.JSONDecodeError):
180
+ print(
181
+ f"[crypto] Warning: cannot decrypt {enc.name} "
182
+ "(machine changed?). Re-authentication required.",
183
+ file=sys.stderr,
184
+ )
185
+ return None
186
+
187
+ # Fall back to plaintext and auto-migrate
188
+ if path.exists():
189
+ try:
190
+ with open(path) as f:
191
+ data: dict[str, Any] = json.load(f)
192
+ save_encrypted(path, data, key) # migrate
193
+ return data
194
+ except (json.JSONDecodeError, OSError):
195
+ return None
196
+ else:
197
+ if path.exists():
198
+ try:
199
+ with open(path) as f:
200
+ return json.load(f)
201
+ except (json.JSONDecodeError, OSError):
202
+ return None
203
+
204
+ return None
205
+
206
+
207
+ def delete_encrypted(path: Path) -> bool:
208
+ """Delete both encrypted (``.enc``) and plaintext versions of a file."""
209
+ deleted = False
210
+ enc = _enc_path(path)
211
+ if enc.exists():
212
+ enc.unlink()
213
+ deleted = True
214
+ if path.exists():
215
+ path.unlink()
216
+ deleted = True
217
+ return deleted