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/cli.py ADDED
@@ -0,0 +1,1123 @@
1
+ """Main CLI application for Google Workspace."""
2
+
3
+ import os
4
+
5
+ import typer
6
+ from typing import Annotated, Any, Optional
7
+
8
+ from gws import __version__
9
+ from gws.auth.provider import resolve_auth_provider
10
+ from gws.config import Config
11
+ from gws.output import output_json, output_success, output_error
12
+ from gws.exceptions import ExitCode, AuthError
13
+
14
+ # Main app
15
+ app = typer.Typer(
16
+ name="gws-cli",
17
+ help="Google Workspace CLI - Unified management for Google services.",
18
+ no_args_is_help=True,
19
+ add_completion=False,
20
+ )
21
+
22
+
23
+ def version_callback(value: bool) -> None:
24
+ """Print version and exit."""
25
+ if value:
26
+ output_json({"version": __version__})
27
+ raise typer.Exit()
28
+
29
+
30
+ @app.callback()
31
+ def main(
32
+ version: Annotated[
33
+ Optional[bool],
34
+ typer.Option(
35
+ "--version",
36
+ "-v",
37
+ help="Show version and exit.",
38
+ callback=version_callback,
39
+ is_eager=True,
40
+ ),
41
+ ] = None,
42
+ ) -> None:
43
+ """Google Workspace CLI - Manage Docs, Sheets, Slides, Drive, Gmail, Calendar, and Contacts."""
44
+ pass
45
+
46
+
47
+ # ── Auth command group ─────────────────────────────────────────────────
48
+ auth_app = typer.Typer(help="Authentication management.")
49
+ app.add_typer(auth_app, name="auth")
50
+
51
+
52
+ @auth_app.callback(invoke_without_command=True)
53
+ def auth_default(
54
+ ctx: typer.Context,
55
+ force: Annotated[
56
+ bool,
57
+ typer.Option("--force", "-f", help="Force re-authentication by deleting existing token."),
58
+ ] = False,
59
+ account: Annotated[
60
+ Optional[str],
61
+ typer.Option("--account", "-a", envvar="GWS_ACCOUNT", help="Named account to authenticate."),
62
+ ] = None,
63
+ ) -> None:
64
+ """Authenticate with Google services."""
65
+ if ctx.invoked_subcommand is not None:
66
+ return
67
+
68
+ try:
69
+ provider = resolve_auth_provider(account=account)
70
+
71
+ if force:
72
+ deleted = provider.delete_token()
73
+ if deleted:
74
+ typer.echo("Deleted existing token. Starting fresh authentication...", err=True)
75
+
76
+ credentials = provider.get_credentials(force_refresh=force)
77
+
78
+ if credentials and credentials.valid:
79
+ result: dict[str, Any] = {
80
+ "operation": "auth",
81
+ "message": "Authentication successful. Token is valid and stored.",
82
+ }
83
+ result["token_path"] = str(provider.TOKEN_PATH)
84
+ if provider.account_name:
85
+ result["account"] = provider.account_name
86
+ output_success(**result)
87
+ else:
88
+ output_error(
89
+ error_code="AUTH_FAILED",
90
+ operation="auth",
91
+ message="Failed to obtain valid credentials.",
92
+ )
93
+ raise typer.Exit(ExitCode.AUTH_ERROR)
94
+
95
+ except AuthError as e:
96
+ output_error(
97
+ error_code="AUTH_ERROR",
98
+ operation="auth",
99
+ message=str(e),
100
+ details=e.details if hasattr(e, "details") else None,
101
+ )
102
+ raise typer.Exit(ExitCode.AUTH_ERROR)
103
+
104
+
105
+ @auth_app.command("status")
106
+ def auth_status(
107
+ account: Annotated[
108
+ Optional[str],
109
+ typer.Option("--account", "-a", envvar="GWS_ACCOUNT", help="Named account to check."),
110
+ ] = None,
111
+ ) -> None:
112
+ """Check authentication status (non-interactive)."""
113
+ provider = resolve_auth_provider(account=account)
114
+
115
+ is_valid, status_msg, credentials = provider.check_credentials()
116
+
117
+ if is_valid:
118
+ result: dict[str, Any] = {
119
+ "status": "authenticated",
120
+ "message": f"Token is valid ({status_msg}).",
121
+ }
122
+ result["token_path"] = str(provider.TOKEN_PATH)
123
+ if provider.account_name:
124
+ result["account"] = provider.account_name
125
+ output_json(result)
126
+ else:
127
+ result = {
128
+ "status": "not_authenticated",
129
+ "message": f"Authentication required: {status_msg}",
130
+ "hint": "Run 'gws-cli auth' to authenticate.",
131
+ }
132
+ result["token_path"] = str(provider.TOKEN_PATH)
133
+ if provider.account_name:
134
+ result["account"] = provider.account_name
135
+ output_json(result)
136
+ raise typer.Exit(ExitCode.AUTH_ERROR)
137
+
138
+
139
+ @auth_app.command("logout")
140
+ def auth_logout(
141
+ account: Annotated[
142
+ Optional[str],
143
+ typer.Option("--account", "-a", envvar="GWS_ACCOUNT", help="Named account to log out."),
144
+ ] = None,
145
+ ) -> None:
146
+ """Remove stored authentication token."""
147
+ provider = resolve_auth_provider(account=account)
148
+
149
+ if provider.delete_token():
150
+ result: dict[str, Any] = {
151
+ "operation": "auth.logout",
152
+ "message": "Token deleted successfully.",
153
+ }
154
+ if provider.account_name:
155
+ result["account"] = provider.account_name
156
+ output_success(**result)
157
+ else:
158
+ result = {
159
+ "status": "success",
160
+ "operation": "auth.logout",
161
+ "message": "No token to delete.",
162
+ }
163
+ if provider.account_name:
164
+ result["account"] = provider.account_name
165
+ output_json(result)
166
+
167
+
168
+ @auth_app.command("server-login")
169
+ def auth_server_login(
170
+ device: Annotated[
171
+ bool,
172
+ typer.Option("--device", help="Use device flow (for headless/SSH environments)."),
173
+ ] = False,
174
+ account: Annotated[
175
+ Optional[str],
176
+ typer.Option("--account", "-a", envvar="GWS_ACCOUNT", help="Named account."),
177
+ ] = None,
178
+ ) -> None:
179
+ """Authenticate to the oauth-token-relay server.
180
+
181
+ Uses OAuth 2.1 PKCE flow by default.
182
+ Use --device for headless/SSH environments.
183
+ """
184
+ from gws.auth.server import ServerAuthProvider
185
+
186
+ config = Config.load()
187
+ resolved_account = config.resolve_account(account)
188
+ effective = config.load_effective_config(resolved_account)
189
+ server_url = os.environ.get("GWS_SERVER_URL") or effective.server_url
190
+ if not server_url:
191
+ output_error(
192
+ error_code="NOT_CONFIGURED",
193
+ operation="auth.server-login",
194
+ message="No server URL configured.",
195
+ details="Run 'gws-cli config set-mode server --url <url>' first.",
196
+ )
197
+ raise typer.Exit(ExitCode.INVALID_ARGS)
198
+
199
+ try:
200
+ provider = ServerAuthProvider(server_url=server_url, account=resolved_account, config=effective)
201
+ provider.server_login(device_flow=device)
202
+ output_success(
203
+ operation="auth.server-login",
204
+ message="Server authentication successful.",
205
+ server_url=server_url,
206
+ )
207
+ except AuthError as e:
208
+ output_error(
209
+ error_code="AUTH_ERROR",
210
+ operation="auth.server-login",
211
+ message=str(e),
212
+ details=e.details if hasattr(e, "details") else None,
213
+ )
214
+ raise typer.Exit(ExitCode.AUTH_ERROR)
215
+
216
+
217
+ @auth_app.command("server-status")
218
+ def auth_server_status(
219
+ account: Annotated[
220
+ Optional[str],
221
+ typer.Option("--account", "-a", envvar="GWS_ACCOUNT", help="Named account."),
222
+ ] = None,
223
+ ) -> None:
224
+ """Check connection and auth status with the relay server."""
225
+ from gws.auth.server import ServerAuthProvider
226
+
227
+ config = Config.load()
228
+ resolved_account = config.resolve_account(account)
229
+ effective = config.load_effective_config(resolved_account)
230
+ server_url = os.environ.get("GWS_SERVER_URL") or effective.server_url
231
+ if not server_url:
232
+ output_error(
233
+ error_code="NOT_CONFIGURED",
234
+ operation="auth.server-status",
235
+ message="No server URL configured. Mode is 'local'.",
236
+ details="Run 'gws-cli config set-mode server --url <url>' to switch to server mode.",
237
+ )
238
+ raise typer.Exit(ExitCode.INVALID_ARGS)
239
+
240
+ provider = ServerAuthProvider(server_url=server_url, account=resolved_account, config=effective)
241
+ status = provider.server_status()
242
+ output_json({"status": "success", "operation": "auth.server-status", **status})
243
+
244
+
245
+ @auth_app.command("server-logout")
246
+ def auth_server_logout(
247
+ account: Annotated[
248
+ Optional[str],
249
+ typer.Option("--account", "-a", envvar="GWS_ACCOUNT", help="Named account."),
250
+ ] = None,
251
+ ) -> None:
252
+ """Revoke server authentication and remove server token."""
253
+ from gws.auth.server import ServerAuthProvider
254
+
255
+ config = Config.load()
256
+ resolved_account = config.resolve_account(account)
257
+ effective = config.load_effective_config(resolved_account)
258
+ server_url = os.environ.get("GWS_SERVER_URL") or effective.server_url
259
+ if not server_url:
260
+ output_error(
261
+ error_code="NOT_CONFIGURED",
262
+ operation="auth.server-logout",
263
+ message="No server URL configured.",
264
+ )
265
+ raise typer.Exit(ExitCode.INVALID_ARGS)
266
+
267
+ provider = ServerAuthProvider(server_url=server_url, account=resolved_account, config=effective)
268
+ provider.server_logout()
269
+ output_success(
270
+ operation="auth.server-logout",
271
+ message="Server token revoked and removed.",
272
+ )
273
+
274
+
275
+ @auth_app.command("import-credentials")
276
+ def auth_import_credentials(
277
+ path: Annotated[
278
+ str,
279
+ typer.Argument(help="Path to client_secret.json from Google Cloud Console."),
280
+ ],
281
+ account: Annotated[
282
+ Optional[str],
283
+ typer.Option("--account", "-a", envvar="GWS_ACCOUNT", help="Named account."),
284
+ ] = None,
285
+ ) -> None:
286
+ """Import OAuth client credentials and encrypt them for secure storage."""
287
+ import json
288
+ from pathlib import Path
289
+ from gws.auth.oauth import LocalAuthProvider
290
+ from gws.crypto import save_encrypted
291
+
292
+ source = Path(path).expanduser()
293
+ if not source.exists():
294
+ output_error(
295
+ error_code="NOT_FOUND",
296
+ operation="auth.import-credentials",
297
+ message=f"File not found: {source}",
298
+ )
299
+ raise typer.Exit(ExitCode.INVALID_ARGS)
300
+
301
+ try:
302
+ with open(source) as f:
303
+ client_config = json.load(f)
304
+ except (json.JSONDecodeError, OSError) as e:
305
+ output_error(
306
+ error_code="INVALID_FILE",
307
+ operation="auth.import-credentials",
308
+ message=f"Cannot read file: {e}",
309
+ )
310
+ raise typer.Exit(ExitCode.INVALID_ARGS)
311
+
312
+ # Validate structure
313
+ if "installed" not in client_config and "web" not in client_config:
314
+ output_error(
315
+ error_code="INVALID_FORMAT",
316
+ operation="auth.import-credentials",
317
+ message="File must contain 'installed' or 'web' key (Google OAuth client config).",
318
+ )
319
+ raise typer.Exit(ExitCode.INVALID_ARGS)
320
+
321
+ config = Config.load()
322
+ key = config.get_encryption_key()
323
+ dest = LocalAuthProvider.CREDENTIALS_PATH
324
+ save_encrypted(dest, client_config, key)
325
+
326
+ output_success(
327
+ operation="auth.import-credentials",
328
+ message="Client credentials imported and encrypted.",
329
+ credentials_path=str(dest.parent / (dest.name + ".enc")) if key else str(dest),
330
+ )
331
+
332
+
333
+ # ── Account command group ──────────────────────────────────────────────
334
+ account_app = typer.Typer(help="Multi-account management.")
335
+ app.add_typer(account_app, name="account")
336
+
337
+
338
+ @account_app.command("add")
339
+ def account_add(
340
+ name: Annotated[str, typer.Argument(help="Account name (e.g., 'work', 'personal').")],
341
+ display_name: Annotated[
342
+ Optional[str],
343
+ typer.Option("--name", help="Display name for From field in emails."),
344
+ ] = None,
345
+ force: Annotated[
346
+ bool,
347
+ typer.Option("--force", "-f", help="Overwrite existing account."),
348
+ ] = False,
349
+ no_auth: Annotated[
350
+ bool,
351
+ typer.Option("--no-auth", help="Register account without triggering authentication."),
352
+ ] = False,
353
+ ) -> None:
354
+ """Register and authenticate a new named account."""
355
+ config = Config.load()
356
+
357
+ if config.accounts and name in config.accounts.entries and not force:
358
+ output_error(
359
+ error_code="ACCOUNT_EXISTS",
360
+ operation="account.add",
361
+ message=f"Account '{name}' already exists. Use --force to overwrite.",
362
+ )
363
+ raise typer.Exit(ExitCode.INVALID_ARGS)
364
+
365
+ try:
366
+ Config.validate_account_name(name)
367
+ except ValueError as e:
368
+ output_error(
369
+ error_code="INVALID_ARGS",
370
+ operation="account.add",
371
+ message=str(e),
372
+ )
373
+ raise typer.Exit(ExitCode.INVALID_ARGS)
374
+
375
+ config.add_account(name, display_name=display_name or "")
376
+
377
+ if no_auth:
378
+ output_success(
379
+ operation="account.add",
380
+ message=f"Account '{name}' registered (authentication deferred).",
381
+ account=name,
382
+ is_default=config.accounts.default_account == name if config.accounts else False,
383
+ hint="Run 'gws-cli auth -a {name}' or use any command with '-a {name}' to authenticate.".format(name=name),
384
+ )
385
+ return
386
+
387
+ # Trigger authentication for the new account
388
+ try:
389
+ provider = resolve_auth_provider(account=name, config=config)
390
+ credentials = provider.get_credentials()
391
+
392
+ if credentials and credentials.valid:
393
+ result: dict[str, Any] = {
394
+ "operation": "account.add",
395
+ "message": f"Account '{name}' added and authenticated.",
396
+ "account": name,
397
+ "is_default": config.accounts.default_account == name if config.accounts else False,
398
+ }
399
+ result["token_path"] = str(provider.TOKEN_PATH)
400
+ output_success(**result)
401
+ else:
402
+ # Auth didn't produce valid credentials — keep account, warn user
403
+ output_success(
404
+ operation="account.add",
405
+ message=f"Account '{name}' registered but authentication incomplete.",
406
+ account=name,
407
+ is_default=config.accounts.default_account == name if config.accounts else False,
408
+ hint=f"Authenticate later with 'gws-cli auth -a {name}' or any command with '-a {name}'.",
409
+ )
410
+ except AuthError as e:
411
+ # Auth failed — keep account registered, warn user
412
+ output_success(
413
+ operation="account.add",
414
+ message=f"Account '{name}' registered (authentication skipped: {e}).",
415
+ account=name,
416
+ is_default=config.accounts.default_account == name if config.accounts else False,
417
+ hint=f"Authenticate later with 'gws-cli auth -a {name}' or any command with '-a {name}'.",
418
+ )
419
+
420
+
421
+ @account_app.command("update")
422
+ def account_update(
423
+ name: Annotated[str, typer.Argument(help="Account name to update.")],
424
+ display_name: Annotated[
425
+ Optional[str],
426
+ typer.Option("--name", help="Display name for From field in emails."),
427
+ ] = None,
428
+ email: Annotated[
429
+ Optional[str],
430
+ typer.Option("--email", help="Email address metadata."),
431
+ ] = None,
432
+ ) -> None:
433
+ """Update account metadata (display name, email)."""
434
+ config = Config.load()
435
+
436
+ if display_name is None and email is None:
437
+ output_error(
438
+ error_code="INVALID_ARGS",
439
+ operation="account.update",
440
+ message="Provide at least one of --name or --email.",
441
+ )
442
+ raise typer.Exit(ExitCode.INVALID_ARGS)
443
+
444
+ if config.update_account(name, display_name=display_name, email=email):
445
+ updated = {}
446
+ if display_name is not None:
447
+ updated["name"] = display_name
448
+ if email is not None:
449
+ updated["email"] = email
450
+ output_success(
451
+ operation="account.update",
452
+ message=f"Account '{name}' updated.",
453
+ account=name,
454
+ **updated,
455
+ )
456
+ else:
457
+ output_error(
458
+ error_code="NOT_FOUND",
459
+ operation="account.update",
460
+ message=f"Account '{name}' not found.",
461
+ )
462
+ raise typer.Exit(ExitCode.NOT_FOUND)
463
+
464
+
465
+ @account_app.command("remove")
466
+ def account_remove(
467
+ name: Annotated[str, typer.Argument(help="Account name to remove.")],
468
+ ) -> None:
469
+ """Remove a named account and its credentials."""
470
+ config = Config.load()
471
+
472
+ if config.remove_account(name):
473
+ output_success(
474
+ operation="account.remove",
475
+ message=f"Account '{name}' removed.",
476
+ account=name,
477
+ )
478
+ else:
479
+ output_error(
480
+ error_code="NOT_FOUND",
481
+ operation="account.remove",
482
+ message=f"Account '{name}' not found.",
483
+ )
484
+ raise typer.Exit(ExitCode.NOT_FOUND)
485
+
486
+
487
+ @account_app.command("list")
488
+ def account_list() -> None:
489
+ """List all configured accounts."""
490
+ config = Config.load()
491
+ accounts = config.list_accounts()
492
+
493
+ output_json({
494
+ "status": "success",
495
+ "operation": "account.list",
496
+ "accounts": accounts,
497
+ "count": len(accounts),
498
+ "default": config.accounts.default_account if config.accounts else None,
499
+ })
500
+
501
+
502
+ @account_app.command("default")
503
+ def account_default(
504
+ name: Annotated[str, typer.Argument(help="Account name to set as default.")],
505
+ ) -> None:
506
+ """Set the default account."""
507
+ config = Config.load()
508
+
509
+ if config.set_default_account(name):
510
+ output_success(
511
+ operation="account.default",
512
+ message=f"Default account set to '{name}'.",
513
+ account=name,
514
+ )
515
+ else:
516
+ output_error(
517
+ error_code="NOT_FOUND",
518
+ operation="account.default",
519
+ message=f"Account '{name}' not found.",
520
+ )
521
+ raise typer.Exit(ExitCode.NOT_FOUND)
522
+
523
+
524
+ @account_app.command("config")
525
+ def account_config_show(
526
+ name: Annotated[str, typer.Argument(help="Account name.")],
527
+ ) -> None:
528
+ """Show effective configuration for an account."""
529
+ config = Config.load()
530
+ if not config.accounts or name not in config.accounts.entries:
531
+ output_error(
532
+ error_code="NOT_FOUND",
533
+ operation="account.config",
534
+ message=f"Account '{name}' not found.",
535
+ )
536
+ raise typer.Exit(ExitCode.NOT_FOUND)
537
+
538
+ effective = config.load_effective_config(name)
539
+ overrides = config.load_account_config(name)
540
+
541
+ output_json({
542
+ "status": "success",
543
+ "operation": "account.config",
544
+ "account": name,
545
+ "effective_config": {
546
+ "enabled_services": effective.enabled_services,
547
+ "kroki_url": effective.kroki_url,
548
+ "security_enabled": effective.security_enabled,
549
+ },
550
+ "has_overrides": bool(overrides),
551
+ "overrides": overrides if overrides else None,
552
+ })
553
+
554
+
555
+ @account_app.command("config-enable")
556
+ def account_config_enable(
557
+ name: Annotated[str, typer.Argument(help="Account name.")],
558
+ service: Annotated[str, typer.Argument(help="Service to enable for this account.")],
559
+ ) -> None:
560
+ """Enable a service for a specific account (override)."""
561
+ config = Config.load()
562
+
563
+ if not config.accounts or name not in config.accounts.entries:
564
+ output_error(
565
+ error_code="NOT_FOUND",
566
+ operation="account.config.enable",
567
+ message=f"Account '{name}' not found.",
568
+ )
569
+ raise typer.Exit(ExitCode.NOT_FOUND)
570
+
571
+ if service not in Config.ALL_SERVICES:
572
+ output_error(
573
+ error_code="INVALID_SERVICE",
574
+ operation="account.config.enable",
575
+ message=f"Unknown service: {service}",
576
+ details={"valid_services": Config.ALL_SERVICES},
577
+ )
578
+ raise typer.Exit(ExitCode.INVALID_ARGS)
579
+
580
+ overrides = config.load_account_config(name)
581
+ services = overrides.get("enabled_services", config.enabled_services.copy())
582
+ if service not in services:
583
+ services.append(service)
584
+ overrides["enabled_services"] = services
585
+ config.save_account_config(name, overrides)
586
+
587
+ output_success(
588
+ operation="account.config.enable",
589
+ account=name,
590
+ message=f"Service '{service}' enabled for account '{name}'.",
591
+ enabled_services=services,
592
+ )
593
+
594
+
595
+ @account_app.command("config-disable")
596
+ def account_config_disable(
597
+ name: Annotated[str, typer.Argument(help="Account name.")],
598
+ service: Annotated[str, typer.Argument(help="Service to disable for this account.")],
599
+ ) -> None:
600
+ """Disable a service for a specific account (override)."""
601
+ config = Config.load()
602
+
603
+ if not config.accounts or name not in config.accounts.entries:
604
+ output_error(
605
+ error_code="NOT_FOUND",
606
+ operation="account.config.disable",
607
+ message=f"Account '{name}' not found.",
608
+ )
609
+ raise typer.Exit(ExitCode.NOT_FOUND)
610
+
611
+ if service not in Config.ALL_SERVICES:
612
+ output_error(
613
+ error_code="INVALID_SERVICE",
614
+ operation="account.config.disable",
615
+ message=f"Unknown service: {service}",
616
+ details={"valid_services": Config.ALL_SERVICES},
617
+ )
618
+ raise typer.Exit(ExitCode.INVALID_ARGS)
619
+
620
+ overrides = config.load_account_config(name)
621
+ services = overrides.get("enabled_services", config.enabled_services.copy())
622
+ if service in services:
623
+ services.remove(service)
624
+ overrides["enabled_services"] = services
625
+ config.save_account_config(name, overrides)
626
+
627
+ output_success(
628
+ operation="account.config.disable",
629
+ account=name,
630
+ message=f"Service '{service}' disabled for account '{name}'.",
631
+ enabled_services=services,
632
+ )
633
+
634
+
635
+ @account_app.command("set-readonly")
636
+ def account_set_readonly(
637
+ name: Annotated[str, typer.Argument(help="Account name.")],
638
+ ) -> None:
639
+ """Restrict an account to read-only operations."""
640
+ config = Config.load()
641
+
642
+ if not config.accounts or name not in config.accounts.entries:
643
+ output_error(
644
+ error_code="NOT_FOUND",
645
+ operation="account.set-readonly",
646
+ message=f"Account '{name}' not found.",
647
+ )
648
+ raise typer.Exit(ExitCode.NOT_FOUND)
649
+
650
+ overrides = config.load_account_config(name)
651
+ overrides["allowed_operations"] = Config.READ_ONLY_OPS
652
+ overrides["read_only"] = True
653
+ config.save_account_config(name, overrides)
654
+
655
+ from gws.crypto import delete_encrypted
656
+ token_path = config.get_account_dir(name) / "token.json"
657
+ delete_encrypted(token_path)
658
+
659
+ output_success(
660
+ operation="account.set-readonly",
661
+ account=name,
662
+ message=f"Account '{name}' is now read-only.",
663
+ allowed_operations=Config.READ_ONLY_OPS,
664
+ note="Token cleared — next API call will re-authenticate with read-only scopes.",
665
+ )
666
+
667
+
668
+ @account_app.command("unset-readonly")
669
+ def account_unset_readonly(
670
+ name: Annotated[str, typer.Argument(help="Account name.")],
671
+ ) -> None:
672
+ """Remove read-only restriction from an account."""
673
+ config = Config.load()
674
+
675
+ if not config.accounts or name not in config.accounts.entries:
676
+ output_error(
677
+ error_code="NOT_FOUND",
678
+ operation="account.unset-readonly",
679
+ message=f"Account '{name}' not found.",
680
+ )
681
+ raise typer.Exit(ExitCode.NOT_FOUND)
682
+
683
+ overrides = config.load_account_config(name)
684
+ if "allowed_operations" in overrides:
685
+ del overrides["allowed_operations"]
686
+ if "read_only" in overrides:
687
+ del overrides["read_only"]
688
+ if overrides:
689
+ config.save_account_config(name, overrides)
690
+ else:
691
+ config.clear_account_config(name)
692
+
693
+ from gws.crypto import delete_encrypted
694
+ token_path = config.get_account_dir(name) / "token.json"
695
+ delete_encrypted(token_path)
696
+
697
+ output_success(
698
+ operation="account.unset-readonly",
699
+ account=name,
700
+ message=f"Account '{name}' is no longer read-only. All operations allowed.",
701
+ note="Token cleared — next API call will re-authenticate with full scopes.",
702
+ )
703
+
704
+
705
+ @account_app.command("config-reset")
706
+ def account_config_reset(
707
+ name: Annotated[str, typer.Argument(help="Account name.")],
708
+ ) -> None:
709
+ """Remove all per-account overrides (inherit global config)."""
710
+ config = Config.load()
711
+
712
+ if not config.accounts or name not in config.accounts.entries:
713
+ output_error(
714
+ error_code="NOT_FOUND",
715
+ operation="account.config.reset",
716
+ message=f"Account '{name}' not found.",
717
+ )
718
+ raise typer.Exit(ExitCode.NOT_FOUND)
719
+
720
+ config.clear_account_config(name)
721
+
722
+ output_success(
723
+ operation="account.config.reset",
724
+ account=name,
725
+ message=f"Per-account overrides cleared for '{name}'. Using global config.",
726
+ )
727
+
728
+
729
+ # ── Config command group ───────────────────────────────────────────────
730
+ config_app = typer.Typer(help="Service configuration management.")
731
+ app.add_typer(config_app, name="config")
732
+
733
+
734
+ @config_app.callback(invoke_without_command=True)
735
+ def config_default(ctx: typer.Context) -> None:
736
+ """Manage service configuration."""
737
+ if ctx.invoked_subcommand is None:
738
+ # Default: show current config
739
+ config = Config.load()
740
+ result: dict[str, Any] = {
741
+ "status": "success",
742
+ "operation": "config",
743
+ "mode": config.mode,
744
+ "enabled_services": config.enabled_services,
745
+ "all_services": Config.ALL_SERVICES,
746
+ "kroki_url": config.kroki_url,
747
+ "security_enabled": config.security_enabled,
748
+ "allowlisted_documents": config.allowlisted_documents,
749
+ "allowlisted_emails": config.allowlisted_emails,
750
+ "disabled_security_services": config.disabled_security_services,
751
+ "disabled_security_operations": config.disabled_security_operations,
752
+ }
753
+ if config.server_url:
754
+ result["server_url"] = config.server_url
755
+ if config.is_multi_account:
756
+ result["accounts"] = config.list_accounts()
757
+ result["default_account"] = config.accounts.default_account if config.accounts else None
758
+ output_json(result)
759
+
760
+
761
+ @config_app.command("list")
762
+ def config_list() -> None:
763
+ """List all services and their status."""
764
+ config = Config.load()
765
+ services = {
766
+ service: service in config.enabled_services
767
+ for service in Config.ALL_SERVICES
768
+ }
769
+ output_json({
770
+ "status": "success",
771
+ "operation": "config.list",
772
+ "services": services,
773
+ "enabled_count": len(config.enabled_services),
774
+ "total_count": len(Config.ALL_SERVICES),
775
+ })
776
+
777
+
778
+ @config_app.command("enable")
779
+ def config_enable(
780
+ service: Annotated[str, typer.Argument(help="Service name to enable.")],
781
+ ) -> None:
782
+ """Enable a service."""
783
+ config = Config.load()
784
+
785
+ if service not in Config.ALL_SERVICES:
786
+ output_error(
787
+ error_code="INVALID_SERVICE",
788
+ operation="config.enable",
789
+ message=f"Unknown service: {service}",
790
+ details={"valid_services": Config.ALL_SERVICES},
791
+ )
792
+ raise typer.Exit(ExitCode.INVALID_ARGS)
793
+
794
+ if config.enable_service(service):
795
+ output_success(
796
+ operation="config.enable",
797
+ message=f"Service '{service}' enabled.",
798
+ enabled_services=config.enabled_services,
799
+ )
800
+ else:
801
+ output_json({
802
+ "status": "success",
803
+ "operation": "config.enable",
804
+ "message": f"Service '{service}' was already enabled.",
805
+ "enabled_services": config.enabled_services,
806
+ })
807
+
808
+
809
+ @config_app.command("disable")
810
+ def config_disable(
811
+ service: Annotated[str, typer.Argument(help="Service name to disable.")],
812
+ ) -> None:
813
+ """Disable a service."""
814
+ config = Config.load()
815
+
816
+ if service not in Config.ALL_SERVICES:
817
+ output_error(
818
+ error_code="INVALID_SERVICE",
819
+ operation="config.disable",
820
+ message=f"Unknown service: {service}",
821
+ details={"valid_services": Config.ALL_SERVICES},
822
+ )
823
+ raise typer.Exit(ExitCode.INVALID_ARGS)
824
+
825
+ if config.disable_service(service):
826
+ output_success(
827
+ operation="config.disable",
828
+ message=f"Service '{service}' disabled.",
829
+ enabled_services=config.enabled_services,
830
+ )
831
+ else:
832
+ output_json({
833
+ "status": "success",
834
+ "operation": "config.disable",
835
+ "message": f"Service '{service}' was already disabled.",
836
+ "enabled_services": config.enabled_services,
837
+ })
838
+
839
+
840
+ @config_app.command("reset")
841
+ def config_reset() -> None:
842
+ """Reset configuration to defaults (all services enabled)."""
843
+ config = Config.load()
844
+ config.enabled_services = list(Config.ALL_SERVICES)
845
+ config.kroki_url = Config.DEFAULT_KROKI_URL
846
+ config.save()
847
+
848
+ output_success(
849
+ operation="config.reset",
850
+ message="Configuration reset to defaults.",
851
+ enabled_services=config.enabled_services,
852
+ kroki_url=config.kroki_url,
853
+ )
854
+
855
+
856
+ @config_app.command("set-kroki")
857
+ def config_set_kroki(
858
+ url: Annotated[str, typer.Argument(help="Kroki server URL (e.g., http://localhost:8000).")],
859
+ ) -> None:
860
+ """Set the Kroki server URL for diagram rendering.
861
+
862
+ Default is https://kroki.io (public server).
863
+ Set a custom URL if you run a local Kroki instance.
864
+ """
865
+ config = Config.load()
866
+ config.kroki_url = url.rstrip("/")
867
+ config.save()
868
+
869
+ output_success(
870
+ operation="config.set-kroki",
871
+ message=f"Kroki URL set to: {config.kroki_url}",
872
+ kroki_url=config.kroki_url,
873
+ )
874
+
875
+
876
+ @config_app.command("allowlist-add")
877
+ def config_allowlist_add(
878
+ type_: Annotated[str, typer.Argument(help="Type: 'docs' or 'email'.", metavar="TYPE")],
879
+ id_: Annotated[str, typer.Argument(help="Document ID or email message ID.", metavar="ID")],
880
+ ) -> None:
881
+ """Add an ID to the security allowlist.
882
+
883
+ Allowlisted documents and emails skip security wrapping.
884
+
885
+ Examples:
886
+ gws-cli config allowlist-add docs 1abc2def3ghi
887
+ gws-cli config allowlist-add email 18fd9a8b2c3d4e5f
888
+ """
889
+ config = Config.load()
890
+
891
+ if type_ == "docs":
892
+ if id_ not in config.allowlisted_documents:
893
+ config.allowlisted_documents.append(id_)
894
+ config.save()
895
+ output_success(
896
+ operation="config.allowlist-add",
897
+ type="docs",
898
+ id=id_,
899
+ message=f"Document {id_} added to allowlist.",
900
+ allowlisted_documents=config.allowlisted_documents,
901
+ )
902
+ else:
903
+ output_json({
904
+ "status": "success",
905
+ "operation": "config.allowlist-add",
906
+ "message": f"Document {id_} already in allowlist.",
907
+ })
908
+ elif type_ == "email":
909
+ if id_ not in config.allowlisted_emails:
910
+ config.allowlisted_emails.append(id_)
911
+ config.save()
912
+ output_success(
913
+ operation="config.allowlist-add",
914
+ type="email",
915
+ id=id_,
916
+ message=f"Email {id_} added to allowlist.",
917
+ allowlisted_emails=config.allowlisted_emails,
918
+ )
919
+ else:
920
+ output_json({
921
+ "status": "success",
922
+ "operation": "config.allowlist-add",
923
+ "message": f"Email {id_} already in allowlist.",
924
+ })
925
+ else:
926
+ output_error(
927
+ error_code="INVALID_TYPE",
928
+ operation="config.allowlist-add",
929
+ message=f"Unknown type: {type_}. Use 'docs' or 'email'.",
930
+ )
931
+ raise typer.Exit(ExitCode.INVALID_ARGS)
932
+
933
+
934
+ @config_app.command("allowlist-remove")
935
+ def config_allowlist_remove(
936
+ type_: Annotated[str, typer.Argument(help="Type: 'docs' or 'email'.", metavar="TYPE")],
937
+ id_: Annotated[str, typer.Argument(help="Document ID or email message ID.", metavar="ID")],
938
+ ) -> None:
939
+ """Remove an ID from the security allowlist.
940
+
941
+ Examples:
942
+ gws-cli config allowlist-remove docs 1abc2def3ghi
943
+ gws-cli config allowlist-remove email 18fd9a8b2c3d4e5f
944
+ """
945
+ config = Config.load()
946
+
947
+ if type_ == "docs":
948
+ if id_ in config.allowlisted_documents:
949
+ config.allowlisted_documents.remove(id_)
950
+ config.save()
951
+ output_success(
952
+ operation="config.allowlist-remove",
953
+ type="docs",
954
+ id=id_,
955
+ message=f"Document {id_} removed from allowlist.",
956
+ allowlisted_documents=config.allowlisted_documents,
957
+ )
958
+ else:
959
+ output_json({
960
+ "status": "success",
961
+ "operation": "config.allowlist-remove",
962
+ "message": f"Document {id_} was not in allowlist.",
963
+ })
964
+ elif type_ == "email":
965
+ if id_ in config.allowlisted_emails:
966
+ config.allowlisted_emails.remove(id_)
967
+ config.save()
968
+ output_success(
969
+ operation="config.allowlist-remove",
970
+ type="email",
971
+ id=id_,
972
+ message=f"Email {id_} removed from allowlist.",
973
+ allowlisted_emails=config.allowlisted_emails,
974
+ )
975
+ else:
976
+ output_json({
977
+ "status": "success",
978
+ "operation": "config.allowlist-remove",
979
+ "message": f"Email {id_} was not in allowlist.",
980
+ })
981
+ else:
982
+ output_error(
983
+ error_code="INVALID_TYPE",
984
+ operation="config.allowlist-remove",
985
+ message=f"Unknown type: {type_}. Use 'docs' or 'email'.",
986
+ )
987
+ raise typer.Exit(ExitCode.INVALID_ARGS)
988
+
989
+
990
+ @config_app.command("allowlist-list")
991
+ def config_allowlist_list() -> None:
992
+ """List all IDs in the security allowlist."""
993
+ config = Config.load()
994
+ output_success(
995
+ operation="config.allowlist-list",
996
+ allowlisted_documents=config.allowlisted_documents,
997
+ allowlisted_emails=config.allowlisted_emails,
998
+ total_count=len(config.allowlisted_documents) + len(config.allowlisted_emails),
999
+ )
1000
+
1001
+
1002
+ @config_app.command("set-mode")
1003
+ def config_set_mode(
1004
+ mode: Annotated[str, typer.Argument(help="Auth mode: 'local' or 'server'.")],
1005
+ url: Annotated[
1006
+ Optional[str],
1007
+ typer.Option("--url", help="Server URL (required for server mode)."),
1008
+ ] = None,
1009
+ provider: Annotated[
1010
+ Optional[str],
1011
+ typer.Option("--provider", help="Relay provider name (e.g. 'google-workspace'). Required when server has multiple providers."),
1012
+ ] = None,
1013
+ account: Annotated[
1014
+ Optional[str],
1015
+ typer.Option("--account", "-a", help="Set mode for a specific account only."),
1016
+ ] = None,
1017
+ ) -> None:
1018
+ """Switch authentication mode between local and server.
1019
+
1020
+ Local mode: uses client_secret.json for direct OAuth.
1021
+ Server mode: delegates auth to an oauth-token-relay server.
1022
+
1023
+ When --account is specified, the mode is stored as a per-account override.
1024
+ Without --account, it sets the global default for all accounts.
1025
+
1026
+ Examples:
1027
+ gws-cli config set-mode server --url https://auth.company.com
1028
+ gws-cli config set-mode server --url https://auth.company.com -a work --provider google-work
1029
+ gws-cli config set-mode local -a personal
1030
+ """
1031
+ if mode not in ("local", "server"):
1032
+ output_error(
1033
+ error_code="INVALID_ARGS",
1034
+ operation="config.set-mode",
1035
+ message=f"Invalid mode: {mode}. Use 'local' or 'server'.",
1036
+ )
1037
+ raise typer.Exit(ExitCode.INVALID_ARGS)
1038
+
1039
+ if mode == "server" and not url:
1040
+ # Check if there's already a global server_url to inherit
1041
+ config = Config.load()
1042
+ if not config.server_url:
1043
+ output_error(
1044
+ error_code="INVALID_ARGS",
1045
+ operation="config.set-mode",
1046
+ message="Server mode requires --url (no global server_url to inherit).",
1047
+ )
1048
+ raise typer.Exit(ExitCode.INVALID_ARGS)
1049
+
1050
+ config = Config.load()
1051
+
1052
+ if account:
1053
+ # Auto-create account if it doesn't exist (convenience for setup)
1054
+ if account not in (config.accounts.entries if config.accounts else {}):
1055
+ try:
1056
+ Config.validate_account_name(account)
1057
+ except ValueError as e:
1058
+ output_error(
1059
+ error_code="INVALID_ARGS",
1060
+ operation="config.set-mode",
1061
+ message=str(e),
1062
+ )
1063
+ raise typer.Exit(ExitCode.INVALID_ARGS)
1064
+ config.add_account(account)
1065
+
1066
+ overrides = config.load_account_config(account)
1067
+ overrides["mode"] = mode
1068
+ if url:
1069
+ overrides["server_url"] = url.rstrip("/")
1070
+ elif mode == "local":
1071
+ overrides.pop("server_url", None)
1072
+ if provider is not None:
1073
+ overrides["server_provider"] = provider
1074
+ elif mode == "local":
1075
+ overrides.pop("server_provider", None)
1076
+ config.save_account_config(account, overrides)
1077
+
1078
+ # Clear Google token so next API call re-authenticates via the new mode
1079
+ from gws.crypto import delete_encrypted
1080
+ token_path = config.get_account_dir(account) / "token.json"
1081
+ token_cleared = delete_encrypted(token_path)
1082
+ else:
1083
+ # Global config
1084
+ config.mode = mode
1085
+ config.server_url = url.rstrip("/") if url else None
1086
+ config.server_provider = provider
1087
+ config.save()
1088
+ token_cleared = False
1089
+
1090
+ result: dict[str, Any] = {
1091
+ "operation": "config.set-mode",
1092
+ "message": f"Auth mode set to '{mode}'.",
1093
+ "mode": mode,
1094
+ }
1095
+ if account:
1096
+ result["account"] = account
1097
+ result["scope"] = "per-account"
1098
+ else:
1099
+ result["scope"] = "global"
1100
+ if url:
1101
+ result["server_url"] = url.rstrip("/") if url else None
1102
+ if provider:
1103
+ result["server_provider"] = provider
1104
+ if token_cleared:
1105
+ result["note"] = "Token cleared — next API call will re-authenticate via the new mode."
1106
+ output_success(**result)
1107
+
1108
+
1109
+ # Register service command groups
1110
+ from gws.commands import drive, docs, sheets, slides, gmail, calendar, contacts, convert # noqa: E402
1111
+
1112
+ app.add_typer(drive.app, name="drive")
1113
+ app.add_typer(docs.app, name="docs")
1114
+ app.add_typer(sheets.app, name="sheets")
1115
+ app.add_typer(slides.app, name="slides")
1116
+ app.add_typer(gmail.app, name="gmail")
1117
+ app.add_typer(calendar.app, name="calendar")
1118
+ app.add_typer(contacts.app, name="contacts")
1119
+ app.add_typer(convert.app, name="convert")
1120
+
1121
+
1122
+ if __name__ == "__main__":
1123
+ app()