gws-cli 1.3.0__tar.gz → 1.4.0__tar.gz

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 (77) hide show
  1. {gws_cli-1.3.0 → gws_cli-1.4.0}/PKG-INFO +1 -1
  2. {gws_cli-1.3.0 → gws_cli-1.4.0}/SKILL-advanced.md +3 -3
  3. {gws_cli-1.3.0 → gws_cli-1.4.0}/SKILL.md +20 -3
  4. {gws_cli-1.3.0 → gws_cli-1.4.0}/pyproject.toml +1 -1
  5. {gws_cli-1.3.0 → gws_cli-1.4.0}/reference/gmail.md +2 -0
  6. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/__init__.py +1 -1
  7. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/auth/oauth.py +35 -1
  8. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/auth/provider.py +4 -1
  9. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/auth/server.py +29 -1
  10. gws_cli-1.4.0/src/gws/cli.py +65 -0
  11. gws_cli-1.4.0/src/gws/commands/account.py +403 -0
  12. gws_cli-1.4.0/src/gws/commands/auth.py +327 -0
  13. gws_cli-1.4.0/src/gws/commands/config.py +402 -0
  14. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/config.py +107 -20
  15. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/crypto.py +2 -2
  16. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/services/gmail.py +33 -24
  17. {gws_cli-1.3.0 → gws_cli-1.4.0}/tests/test_account_commands.py +132 -0
  18. {gws_cli-1.3.0 → gws_cli-1.4.0}/tests/test_auth_provider.py +31 -0
  19. {gws_cli-1.3.0 → gws_cli-1.4.0}/tests/test_config_accounts.py +97 -0
  20. {gws_cli-1.3.0 → gws_cli-1.4.0}/tests/test_crypto.py +14 -0
  21. {gws_cli-1.3.0 → gws_cli-1.4.0}/tests/test_server_auth.py +17 -0
  22. gws_cli-1.3.0/src/gws/cli.py +0 -1124
  23. {gws_cli-1.3.0 → gws_cli-1.4.0}/.gitignore +0 -0
  24. {gws_cli-1.3.0 → gws_cli-1.4.0}/CLAUDE.md +0 -0
  25. {gws_cli-1.3.0 → gws_cli-1.4.0}/COMPARISON-REPORT.md +0 -0
  26. {gws_cli-1.3.0 → gws_cli-1.4.0}/LICENSE +0 -0
  27. {gws_cli-1.3.0 → gws_cli-1.4.0}/LIVE_TESTING.md +0 -0
  28. {gws_cli-1.3.0 → gws_cli-1.4.0}/README.md +0 -0
  29. {gws_cli-1.3.0 → gws_cli-1.4.0}/SKILL-typesetting.md +0 -0
  30. {gws_cli-1.3.0 → gws_cli-1.4.0}/TESTING.md +0 -0
  31. {gws_cli-1.3.0 → gws_cli-1.4.0}/docs/plans/2026-03-07-download-security-gate.md +0 -0
  32. {gws_cli-1.3.0 → gws_cli-1.4.0}/docs/plans/2026-03-07-security-hardening-design.md +0 -0
  33. {gws_cli-1.3.0 → gws_cli-1.4.0}/docs/plans/2026-03-07-security-hardening-plan.md +0 -0
  34. {gws_cli-1.3.0 → gws_cli-1.4.0}/reference/calendar.md +0 -0
  35. {gws_cli-1.3.0 → gws_cli-1.4.0}/reference/contacts.md +0 -0
  36. {gws_cli-1.3.0 → gws_cli-1.4.0}/reference/docs.md +0 -0
  37. {gws_cli-1.3.0 → gws_cli-1.4.0}/reference/drive.md +0 -0
  38. {gws_cli-1.3.0 → gws_cli-1.4.0}/reference/sheets.md +0 -0
  39. {gws_cli-1.3.0 → gws_cli-1.4.0}/reference/slides.md +0 -0
  40. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/__main__.py +0 -0
  41. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/auth/__init__.py +0 -0
  42. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/auth/scopes.py +0 -0
  43. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/commands/__init__.py +0 -0
  44. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/commands/_account.py +0 -0
  45. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/commands/calendar.py +0 -0
  46. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/commands/contacts.py +0 -0
  47. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/commands/convert.py +0 -0
  48. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/commands/docs.py +0 -0
  49. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/commands/drive.py +0 -0
  50. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/commands/gmail.py +0 -0
  51. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/commands/sheets.py +0 -0
  52. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/commands/slides.py +0 -0
  53. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/context.py +0 -0
  54. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/exceptions.py +0 -0
  55. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/output.py +0 -0
  56. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/services/__init__.py +0 -0
  57. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/services/base.py +0 -0
  58. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/services/calendar.py +0 -0
  59. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/services/contacts.py +0 -0
  60. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/services/convert.py +0 -0
  61. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/services/docs.py +0 -0
  62. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/services/drive.py +0 -0
  63. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/services/sheets.py +0 -0
  64. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/services/slides.py +0 -0
  65. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/utils/__init__.py +0 -0
  66. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/utils/colors.py +0 -0
  67. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/utils/diagrams.py +0 -0
  68. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/utils/retry.py +0 -0
  69. {gws_cli-1.3.0 → gws_cli-1.4.0}/src/gws/utils/security.py +0 -0
  70. {gws_cli-1.3.0 → gws_cli-1.4.0}/tests/__init__.py +0 -0
  71. {gws_cli-1.3.0 → gws_cli-1.4.0}/tests/conftest.py +0 -0
  72. {gws_cli-1.3.0 → gws_cli-1.4.0}/tests/test_account_enforcement.py +0 -0
  73. {gws_cli-1.3.0 → gws_cli-1.4.0}/tests/test_auth_accounts.py +0 -0
  74. {gws_cli-1.3.0 → gws_cli-1.4.0}/tests/test_docs.py +0 -0
  75. {gws_cli-1.3.0 → gws_cli-1.4.0}/tests/test_download_screening.py +0 -0
  76. {gws_cli-1.3.0 → gws_cli-1.4.0}/tests/test_gmail_mime.py +0 -0
  77. {gws_cli-1.3.0 → gws_cli-1.4.0}/tests/test_output.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gws-cli
3
- Version: 1.3.0
3
+ Version: 1.4.0
4
4
  Summary: Google Workspace CLI - Unified management for Docs, Sheets, Slides, Drive, Gmail, Calendar, and Contacts
5
5
  Project-URL: Homepage, https://github.com/andmarios/google-workspace-skill
6
6
  Project-URL: Repository, https://github.com/andmarios/google-workspace-skill
@@ -396,9 +396,9 @@ uvx gws-cli drive search "name contains 'report'"
396
396
  3. **Concurrent request limit**: Too many parallel requests
397
397
 
398
398
  ```bash
399
- # For bulk email operations, process in batches of 50
400
- # The gws CLI handles batching internally for list operations
401
- uvx gws-cli gmail list --max 100 # Internally batched
399
+ # The CLI automatically chunks batch requests into groups of 100.
400
+ # Values up to 500 work, but prefer ≤50 to avoid rate-limiting.
401
+ uvx gws-cli gmail list --max 50
402
402
  ```
403
403
 
404
404
  ### Google Calendar: Event ID Strategy
@@ -328,16 +328,33 @@ All commands use `uvx gws-cli <service> <command>`. Authentication is automatic
328
328
  > **Important**: `gws-cli auth` and `gws-cli auth --force` open a browser for OAuth. These must be run by the user in their terminal, not from Claude Code.
329
329
 
330
330
  ```bash
331
- uvx gws-cli auth # Authenticate (opens browser)
332
- uvx gws-cli auth status # Check auth status
331
+ uvx gws-cli auth # Authenticate using the configured mode (opens browser)
332
+ uvx gws-cli auth status # Check auth status — reports the active mode
333
333
  uvx gws-cli auth --force # Force re-authentication (opens browser)
334
- uvx gws-cli auth logout # Logout
334
+ uvx gws-cli auth logout # Logout (best-effort revokes the token upstream)
335
335
  # Auth commands support --account for multi-account
336
336
  uvx gws-cli auth status --account work
337
337
  ```
338
338
 
339
339
  Credentials stored in `~/.config/gws-cli/` (`client_secret.json`, `token.json`, `gws_config.json`).
340
340
 
341
+ ### Auth modes: local vs server
342
+
343
+ `gws-cli auth` (with no subcommand) logs in using the configured **mode**:
344
+
345
+ - **local** (default) — direct OAuth with your own `client_secret.json` via a browser loopback flow.
346
+ - **server** — delegates auth to an `oauth-token-relay` server (no local OAuth client needed).
347
+
348
+ `auth status` reports the active mode, and `account list` shows the mode per account. Switch with:
349
+
350
+ ```bash
351
+ uvx gws-cli config set-mode local # Use local OAuth (default)
352
+ uvx gws-cli config set-mode server --url <relay-url> # Use a relay server
353
+ uvx gws-cli config set-mode local -a personal # Per-account override
354
+ ```
355
+
356
+ Each account can have its own mode; a per-account setting overrides the global default.
357
+
341
358
  ## Multi-Account Support
342
359
 
343
360
  Opt-in named accounts for different Google accounts. `account add` opens a browser — must be run by user.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "gws-cli"
7
- version = "1.3.0"
7
+ version = "1.4.0"
8
8
  description = "Google Workspace CLI - Unified management for Docs, Sheets, Slides, Drive, Gmail, Calendar, and Contacts"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -13,6 +13,8 @@
13
13
 
14
14
  ## Basic Operations
15
15
 
16
+ > **`--max` guideline:** Default is 10. Values up to 500 work (batched internally in groups of 100), but prefer ≤50 to avoid rate-limiting. Start small and paginate with `--query` filters rather than fetching hundreds at once.
17
+
16
18
  ```bash
17
19
  # List recent messages
18
20
  uvx gws-cli gmail list --max 10
@@ -1,3 +1,3 @@
1
1
  """Google Workspace CLI - Unified management for Google services."""
2
2
 
3
- __version__ = "1.3.0"
3
+ __version__ = "1.4.0"
@@ -170,9 +170,43 @@ class LocalAuthProvider:
170
170
  save_encrypted(self.TOKEN_PATH, data, self.config.get_encryption_key())
171
171
 
172
172
  def delete_token(self) -> bool:
173
- """Delete the token file (encrypted and/or plaintext)."""
173
+ """Delete the token file (encrypted and/or plaintext).
174
+
175
+ Best-effort revokes the token upstream at Google first, so that logging
176
+ out actually invalidates access rather than only removing the local
177
+ copy. A failed revoke never blocks the local deletion.
178
+ """
179
+ self._revoke_token_best_effort()
174
180
  return delete_encrypted(self.TOKEN_PATH)
175
181
 
182
+ def _revoke_token_best_effort(self) -> None:
183
+ """Revoke the stored Google token at Google's revoke endpoint.
184
+
185
+ Never raises — logout must succeed even if the network call fails.
186
+ """
187
+ try:
188
+ token_data = load_encrypted(self.TOKEN_PATH, self.config.get_encryption_key())
189
+ except Exception:
190
+ return
191
+ if not token_data:
192
+ return
193
+ # Revoking a refresh token invalidates the whole grant; fall back to the
194
+ # access token if that is all we have.
195
+ token = token_data.get("refresh_token") or token_data.get("token")
196
+ if not token:
197
+ return
198
+ try:
199
+ import httpx
200
+
201
+ httpx.post(
202
+ "https://oauth2.googleapis.com/revoke",
203
+ data={"token": token},
204
+ timeout=5.0,
205
+ )
206
+ except Exception:
207
+ # Best-effort only — a revoke failure must not break logout.
208
+ pass
209
+
176
210
  def check_credentials(self) -> tuple[bool, str, Credentials | None]:
177
211
  """Check credentials without triggering auth flow.
178
212
 
@@ -77,7 +77,10 @@ def resolve_auth_provider(
77
77
  from gws.config import Config
78
78
 
79
79
  cfg = config or Config.load()
80
- resolved_account = account or cfg.resolve_account()
80
+ # Route the explicit account through resolve_account() too, so an invalid
81
+ # name raises the caught AuthError (clean exit) instead of a later raw
82
+ # ValueError from get_account_dir().
83
+ resolved_account = cfg.resolve_account(account)
81
84
 
82
85
  # Apply per-account overrides (mode, server_url, server_provider, etc.)
83
86
  effective = cfg.load_effective_config(resolved_account)
@@ -11,7 +11,7 @@ import time
11
11
  import webbrowser
12
12
  from pathlib import Path
13
13
  from typing import Any
14
- from urllib.parse import urlencode
14
+ from urllib.parse import urlencode, urlparse
15
15
 
16
16
  import httpx
17
17
  from google.oauth2.credentials import Credentials
@@ -21,6 +21,33 @@ from gws.crypto import save_encrypted, load_encrypted, delete_encrypted
21
21
  from gws.exceptions import AuthError
22
22
 
23
23
 
24
+ # Recognised Google OAuth consent hosts the relay may legitimately return.
25
+ _KNOWN_AUTH_HOSTS = {"accounts.google.com"}
26
+
27
+
28
+ def _validate_auth_url(auth_url: str) -> None:
29
+ """Validate a relay-supplied authorization URL before opening a browser.
30
+
31
+ Hard-fails on anything that is not an ``https://`` URL with a host — this
32
+ blocks scheme-downgrade and non-web schemes (``javascript:``, ``file:`` …)
33
+ that a malicious or compromised relay could return. The host is only warned
34
+ on (not blocked) when unrecognised, because the relay legitimately returns
35
+ Google consent URLs and the set of valid hosts may evolve.
36
+ """
37
+ parsed = urlparse(auth_url)
38
+ if parsed.scheme != "https" or not parsed.netloc:
39
+ raise AuthError(
40
+ "Relay returned an unsafe authorization URL",
41
+ f"Refusing to open a non-https URL: {auth_url!r}",
42
+ )
43
+ if parsed.hostname not in _KNOWN_AUTH_HOSTS:
44
+ print(
45
+ f"[gws-cli] Warning: authorization URL host '{parsed.hostname}' is not a "
46
+ "recognised Google OAuth host. Continue only if you trust this relay.",
47
+ file=sys.stderr,
48
+ )
49
+
50
+
24
51
  class ServerAuthProvider:
25
52
  """Auth provider that delegates OAuth to an oauth-token-relay server.
26
53
 
@@ -398,6 +425,7 @@ class ServerAuthProvider:
398
425
 
399
426
  start_data = resp.json()
400
427
  auth_url = start_data["auth_url"]
428
+ _validate_auth_url(auth_url)
401
429
  session_id = start_data["session_id"]
402
430
 
403
431
  print("\n" + "=" * 60, file=sys.stderr)
@@ -0,0 +1,65 @@
1
+ """Main CLI application for Google Workspace."""
2
+
3
+
4
+ import typer
5
+ from typing import Annotated, Optional
6
+
7
+ from gws import __version__
8
+ from gws.output import output_json
9
+
10
+ # Main app
11
+ app = typer.Typer(
12
+ name="gws-cli",
13
+ help="Google Workspace CLI - Unified management for Google services.",
14
+ no_args_is_help=True,
15
+ add_completion=False,
16
+ pretty_exceptions_show_locals=False,
17
+ )
18
+
19
+
20
+ def version_callback(value: bool) -> None:
21
+ """Print version and exit."""
22
+ if value:
23
+ output_json({"version": __version__})
24
+ raise typer.Exit()
25
+
26
+
27
+ @app.callback()
28
+ def main(
29
+ version: Annotated[
30
+ Optional[bool],
31
+ typer.Option(
32
+ "--version",
33
+ "-v",
34
+ help="Show version and exit.",
35
+ callback=version_callback,
36
+ is_eager=True,
37
+ ),
38
+ ] = None,
39
+ ) -> None:
40
+ """Google Workspace CLI - Manage Docs, Sheets, Slides, Drive, Gmail, Calendar, and Contacts."""
41
+ pass
42
+
43
+
44
+ # Register command groups
45
+ from gws.commands import auth, account # noqa: E402
46
+ from gws.commands import config as config_commands # noqa: E402
47
+ from gws.commands import ( # noqa: E402
48
+ drive, docs, sheets, slides, gmail, calendar, contacts, convert,
49
+ )
50
+
51
+ app.add_typer(auth.app, name="auth")
52
+ app.add_typer(account.app, name="account")
53
+ app.add_typer(config_commands.app, name="config")
54
+ app.add_typer(drive.app, name="drive")
55
+ app.add_typer(docs.app, name="docs")
56
+ app.add_typer(sheets.app, name="sheets")
57
+ app.add_typer(slides.app, name="slides")
58
+ app.add_typer(gmail.app, name="gmail")
59
+ app.add_typer(calendar.app, name="calendar")
60
+ app.add_typer(contacts.app, name="contacts")
61
+ app.add_typer(convert.app, name="convert")
62
+
63
+
64
+ if __name__ == "__main__":
65
+ app()
@@ -0,0 +1,403 @@
1
+ """Account command group for gws-cli (multi-account management)."""
2
+
3
+ import typer
4
+ from typing import Annotated, Any, Optional
5
+
6
+ from gws.auth.provider import resolve_auth_provider
7
+ from gws.config import Config
8
+ from gws.output import output_json, output_success, output_error
9
+ from gws.exceptions import ExitCode, AuthError
10
+
11
+
12
+ app = typer.Typer(help="Multi-account management.")
13
+
14
+
15
+ @app.command("add")
16
+ def account_add(
17
+ name: Annotated[str, typer.Argument(help="Account name (e.g., 'work', 'personal').")],
18
+ display_name: Annotated[
19
+ Optional[str],
20
+ typer.Option("--name", help="Display name for From field in emails."),
21
+ ] = None,
22
+ force: Annotated[
23
+ bool,
24
+ typer.Option("--force", "-f", help="Overwrite existing account."),
25
+ ] = False,
26
+ no_auth: Annotated[
27
+ bool,
28
+ typer.Option("--no-auth", help="Register account without triggering authentication."),
29
+ ] = False,
30
+ ) -> None:
31
+ """Register and authenticate a new named account."""
32
+ config = Config.load()
33
+
34
+ if config.accounts and name in config.accounts.entries and not force:
35
+ output_error(
36
+ error_code="ACCOUNT_EXISTS",
37
+ operation="account.add",
38
+ message=f"Account '{name}' already exists. Use --force to overwrite.",
39
+ )
40
+ raise typer.Exit(ExitCode.INVALID_ARGS)
41
+
42
+ try:
43
+ Config.validate_account_name(name)
44
+ except ValueError as e:
45
+ output_error(
46
+ error_code="INVALID_ARGS",
47
+ operation="account.add",
48
+ message=str(e),
49
+ )
50
+ raise typer.Exit(ExitCode.INVALID_ARGS)
51
+
52
+ config.add_account(name, display_name=display_name or "")
53
+
54
+ if no_auth:
55
+ output_success(
56
+ operation="account.add",
57
+ message=f"Account '{name}' registered (authentication deferred).",
58
+ account=name,
59
+ is_default=config.accounts.default_account == name if config.accounts else False,
60
+ hint="Run 'gws-cli auth -a {name}' or use any command with '-a {name}' to authenticate.".format(name=name),
61
+ )
62
+ return
63
+
64
+ # Trigger authentication for the new account
65
+ try:
66
+ provider = resolve_auth_provider(account=name, config=config)
67
+ credentials = provider.get_credentials()
68
+
69
+ if credentials and credentials.valid:
70
+ result: dict[str, Any] = {
71
+ "operation": "account.add",
72
+ "message": f"Account '{name}' added and authenticated.",
73
+ "account": name,
74
+ "is_default": config.accounts.default_account == name if config.accounts else False,
75
+ }
76
+ result["token_path"] = str(provider.TOKEN_PATH)
77
+ output_success(**result)
78
+ else:
79
+ # Auth didn't produce valid credentials — keep account, warn user
80
+ output_success(
81
+ operation="account.add",
82
+ message=f"Account '{name}' registered but authentication incomplete.",
83
+ account=name,
84
+ is_default=config.accounts.default_account == name if config.accounts else False,
85
+ hint=f"Authenticate later with 'gws-cli auth -a {name}' or any command with '-a {name}'.",
86
+ )
87
+ except AuthError as e:
88
+ # Auth failed — keep account registered, warn user
89
+ output_success(
90
+ operation="account.add",
91
+ message=f"Account '{name}' registered (authentication skipped: {e}).",
92
+ account=name,
93
+ is_default=config.accounts.default_account == name if config.accounts else False,
94
+ hint=f"Authenticate later with 'gws-cli auth -a {name}' or any command with '-a {name}'.",
95
+ )
96
+
97
+
98
+ @app.command("update")
99
+ def account_update(
100
+ name: Annotated[str, typer.Argument(help="Account name to update.")],
101
+ display_name: Annotated[
102
+ Optional[str],
103
+ typer.Option("--name", help="Display name for From field in emails."),
104
+ ] = None,
105
+ email: Annotated[
106
+ Optional[str],
107
+ typer.Option("--email", help="Email address metadata."),
108
+ ] = None,
109
+ ) -> None:
110
+ """Update account metadata (display name, email)."""
111
+ config = Config.load()
112
+
113
+ if display_name is None and email is None:
114
+ output_error(
115
+ error_code="INVALID_ARGS",
116
+ operation="account.update",
117
+ message="Provide at least one of --name or --email.",
118
+ )
119
+ raise typer.Exit(ExitCode.INVALID_ARGS)
120
+
121
+ if config.update_account(name, display_name=display_name, email=email):
122
+ updated = {}
123
+ if display_name is not None:
124
+ updated["name"] = display_name
125
+ if email is not None:
126
+ updated["email"] = email
127
+ output_success(
128
+ operation="account.update",
129
+ message=f"Account '{name}' updated.",
130
+ account=name,
131
+ **updated,
132
+ )
133
+ else:
134
+ output_error(
135
+ error_code="NOT_FOUND",
136
+ operation="account.update",
137
+ message=f"Account '{name}' not found.",
138
+ )
139
+ raise typer.Exit(ExitCode.NOT_FOUND)
140
+
141
+
142
+ @app.command("remove")
143
+ def account_remove(
144
+ name: Annotated[str, typer.Argument(help="Account name to remove.")],
145
+ ) -> None:
146
+ """Remove a named account and its credentials."""
147
+ config = Config.load()
148
+
149
+ if config.remove_account(name):
150
+ output_success(
151
+ operation="account.remove",
152
+ message=f"Account '{name}' removed.",
153
+ account=name,
154
+ )
155
+ else:
156
+ output_error(
157
+ error_code="NOT_FOUND",
158
+ operation="account.remove",
159
+ message=f"Account '{name}' not found.",
160
+ )
161
+ raise typer.Exit(ExitCode.NOT_FOUND)
162
+
163
+
164
+ @app.command("list")
165
+ def account_list() -> None:
166
+ """List all configured accounts."""
167
+ config = Config.load()
168
+ accounts = config.list_accounts()
169
+
170
+ output_json({
171
+ "status": "success",
172
+ "operation": "account.list",
173
+ "accounts": accounts,
174
+ "count": len(accounts),
175
+ "default": config.accounts.default_account if config.accounts else None,
176
+ })
177
+
178
+
179
+ @app.command("default")
180
+ def account_default(
181
+ name: Annotated[str, typer.Argument(help="Account name to set as default.")],
182
+ ) -> None:
183
+ """Set the default account."""
184
+ config = Config.load()
185
+
186
+ if config.set_default_account(name):
187
+ output_success(
188
+ operation="account.default",
189
+ message=f"Default account set to '{name}'.",
190
+ account=name,
191
+ )
192
+ else:
193
+ output_error(
194
+ error_code="NOT_FOUND",
195
+ operation="account.default",
196
+ message=f"Account '{name}' not found.",
197
+ )
198
+ raise typer.Exit(ExitCode.NOT_FOUND)
199
+
200
+
201
+ @app.command("config")
202
+ def account_config_show(
203
+ name: Annotated[str, typer.Argument(help="Account name.")],
204
+ ) -> None:
205
+ """Show effective configuration for an account."""
206
+ config = Config.load()
207
+ if not config.accounts or name not in config.accounts.entries:
208
+ output_error(
209
+ error_code="NOT_FOUND",
210
+ operation="account.config",
211
+ message=f"Account '{name}' not found.",
212
+ )
213
+ raise typer.Exit(ExitCode.NOT_FOUND)
214
+
215
+ effective = config.load_effective_config(name)
216
+ overrides = config.load_account_config(name)
217
+
218
+ output_json({
219
+ "status": "success",
220
+ "operation": "account.config",
221
+ "account": name,
222
+ "effective_config": {
223
+ "enabled_services": effective.enabled_services,
224
+ "kroki_url": effective.kroki_url,
225
+ "security_enabled": effective.security_enabled,
226
+ },
227
+ "has_overrides": bool(overrides),
228
+ "overrides": overrides if overrides else None,
229
+ })
230
+
231
+
232
+ @app.command("config-enable")
233
+ def account_config_enable(
234
+ name: Annotated[str, typer.Argument(help="Account name.")],
235
+ service: Annotated[str, typer.Argument(help="Service to enable for this account.")],
236
+ ) -> None:
237
+ """Enable a service for a specific account (override)."""
238
+ config = Config.load()
239
+
240
+ if not config.accounts or name not in config.accounts.entries:
241
+ output_error(
242
+ error_code="NOT_FOUND",
243
+ operation="account.config.enable",
244
+ message=f"Account '{name}' not found.",
245
+ )
246
+ raise typer.Exit(ExitCode.NOT_FOUND)
247
+
248
+ if service not in Config.ALL_SERVICES:
249
+ output_error(
250
+ error_code="INVALID_SERVICE",
251
+ operation="account.config.enable",
252
+ message=f"Unknown service: {service}",
253
+ details={"valid_services": Config.ALL_SERVICES},
254
+ )
255
+ raise typer.Exit(ExitCode.INVALID_ARGS)
256
+
257
+ overrides = config.load_account_config(name)
258
+ services = overrides.get("enabled_services", config.enabled_services.copy())
259
+ if service not in services:
260
+ services.append(service)
261
+ overrides["enabled_services"] = services
262
+ config.save_account_config(name, overrides)
263
+
264
+ output_success(
265
+ operation="account.config.enable",
266
+ account=name,
267
+ message=f"Service '{service}' enabled for account '{name}'.",
268
+ enabled_services=services,
269
+ )
270
+
271
+
272
+ @app.command("config-disable")
273
+ def account_config_disable(
274
+ name: Annotated[str, typer.Argument(help="Account name.")],
275
+ service: Annotated[str, typer.Argument(help="Service to disable for this account.")],
276
+ ) -> None:
277
+ """Disable a service for a specific account (override)."""
278
+ config = Config.load()
279
+
280
+ if not config.accounts or name not in config.accounts.entries:
281
+ output_error(
282
+ error_code="NOT_FOUND",
283
+ operation="account.config.disable",
284
+ message=f"Account '{name}' not found.",
285
+ )
286
+ raise typer.Exit(ExitCode.NOT_FOUND)
287
+
288
+ if service not in Config.ALL_SERVICES:
289
+ output_error(
290
+ error_code="INVALID_SERVICE",
291
+ operation="account.config.disable",
292
+ message=f"Unknown service: {service}",
293
+ details={"valid_services": Config.ALL_SERVICES},
294
+ )
295
+ raise typer.Exit(ExitCode.INVALID_ARGS)
296
+
297
+ overrides = config.load_account_config(name)
298
+ services = overrides.get("enabled_services", config.enabled_services.copy())
299
+ if service in services:
300
+ services.remove(service)
301
+ overrides["enabled_services"] = services
302
+ config.save_account_config(name, overrides)
303
+
304
+ output_success(
305
+ operation="account.config.disable",
306
+ account=name,
307
+ message=f"Service '{service}' disabled for account '{name}'.",
308
+ enabled_services=services,
309
+ )
310
+
311
+
312
+ @app.command("set-readonly")
313
+ def account_set_readonly(
314
+ name: Annotated[str, typer.Argument(help="Account name.")],
315
+ ) -> None:
316
+ """Restrict an account to read-only operations."""
317
+ config = Config.load()
318
+
319
+ if not config.accounts or name not in config.accounts.entries:
320
+ output_error(
321
+ error_code="NOT_FOUND",
322
+ operation="account.set-readonly",
323
+ message=f"Account '{name}' not found.",
324
+ )
325
+ raise typer.Exit(ExitCode.NOT_FOUND)
326
+
327
+ overrides = config.load_account_config(name)
328
+ overrides["allowed_operations"] = Config.READ_ONLY_OPS
329
+ overrides["read_only"] = True
330
+ config.save_account_config(name, overrides)
331
+
332
+ from gws.crypto import delete_encrypted
333
+ token_path = config.get_account_dir(name) / "token.json"
334
+ delete_encrypted(token_path)
335
+
336
+ output_success(
337
+ operation="account.set-readonly",
338
+ account=name,
339
+ message=f"Account '{name}' is now read-only.",
340
+ allowed_operations=Config.READ_ONLY_OPS,
341
+ note="Token cleared — next API call will re-authenticate with read-only scopes.",
342
+ )
343
+
344
+
345
+ @app.command("unset-readonly")
346
+ def account_unset_readonly(
347
+ name: Annotated[str, typer.Argument(help="Account name.")],
348
+ ) -> None:
349
+ """Remove read-only restriction from an account."""
350
+ config = Config.load()
351
+
352
+ if not config.accounts or name not in config.accounts.entries:
353
+ output_error(
354
+ error_code="NOT_FOUND",
355
+ operation="account.unset-readonly",
356
+ message=f"Account '{name}' not found.",
357
+ )
358
+ raise typer.Exit(ExitCode.NOT_FOUND)
359
+
360
+ overrides = config.load_account_config(name)
361
+ if "allowed_operations" in overrides:
362
+ del overrides["allowed_operations"]
363
+ if "read_only" in overrides:
364
+ del overrides["read_only"]
365
+ if overrides:
366
+ config.save_account_config(name, overrides)
367
+ else:
368
+ config.clear_account_config(name)
369
+
370
+ from gws.crypto import delete_encrypted
371
+ token_path = config.get_account_dir(name) / "token.json"
372
+ delete_encrypted(token_path)
373
+
374
+ output_success(
375
+ operation="account.unset-readonly",
376
+ account=name,
377
+ message=f"Account '{name}' is no longer read-only. All operations allowed.",
378
+ note="Token cleared — next API call will re-authenticate with full scopes.",
379
+ )
380
+
381
+
382
+ @app.command("config-reset")
383
+ def account_config_reset(
384
+ name: Annotated[str, typer.Argument(help="Account name.")],
385
+ ) -> None:
386
+ """Remove all per-account overrides (inherit global config)."""
387
+ config = Config.load()
388
+
389
+ if not config.accounts or name not in config.accounts.entries:
390
+ output_error(
391
+ error_code="NOT_FOUND",
392
+ operation="account.config.reset",
393
+ message=f"Account '{name}' not found.",
394
+ )
395
+ raise typer.Exit(ExitCode.NOT_FOUND)
396
+
397
+ config.clear_account_config(name)
398
+
399
+ output_success(
400
+ operation="account.config.reset",
401
+ account=name,
402
+ message=f"Per-account overrides cleared for '{name}'. Using global config.",
403
+ )