gws-cli 1.5.0__tar.gz → 1.6.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.
- {gws_cli-1.5.0 → gws_cli-1.6.0}/LIVE_TESTING.md +4 -2
- {gws_cli-1.5.0 → gws_cli-1.6.0}/PKG-INFO +34 -2
- {gws_cli-1.5.0 → gws_cli-1.6.0}/README.md +28 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/SKILL.md +5 -2
- {gws_cli-1.5.0 → gws_cli-1.6.0}/TESTING.md +1 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/pyproject.toml +6 -1
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/__init__.py +1 -1
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/auth/oauth.py +158 -12
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/auth/provider.py +17 -1
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/auth/server.py +33 -15
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/commands/auth.py +35 -11
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/commands/docs.py +2 -2
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/commands/slides.py +2 -2
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/config.py +26 -6
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/crypto.py +2 -2
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/services/docs.py +2 -2
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/services/slides.py +2 -2
- gws_cli-1.6.0/tests/test_auth_commands.py +50 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/tests/test_config_accounts.py +33 -0
- gws_cli-1.6.0/tests/test_config_runtime_state.py +85 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/tests/test_crypto.py +24 -6
- gws_cli-1.6.0/tests/test_font_size.py +81 -0
- gws_cli-1.6.0/tests/test_force_reauth.py +141 -0
- gws_cli-1.6.0/tests/test_headless_auth.py +353 -0
- gws_cli-1.6.0/tests/test_headless_env.py +95 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/tests/test_server_auth.py +3 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/.gitignore +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/CLAUDE.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/COMPARISON-REPORT.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/LICENSE +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/SKILL-advanced.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/SKILL-typesetting.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/docs/plans/2026-03-07-download-security-gate.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/docs/plans/2026-03-07-security-hardening-design.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/docs/plans/2026-03-07-security-hardening-plan.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/reference/calendar.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/reference/contacts.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/reference/docs.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/reference/drive.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/reference/gmail.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/reference/sheets.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/reference/slides.md +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/__main__.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/auth/__init__.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/auth/scopes.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/cli.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/commands/__init__.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/commands/_account.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/commands/account.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/commands/calendar.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/commands/config.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/commands/contacts.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/commands/convert.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/commands/drive.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/commands/gmail.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/commands/sheets.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/context.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/exceptions.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/output.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/services/__init__.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/services/base.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/services/calendar.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/services/contacts.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/services/convert.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/services/drive.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/services/gmail.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/services/sheets.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/utils/__init__.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/utils/colors.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/utils/diagrams.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/utils/retry.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/src/gws/utils/security.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/tests/__init__.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/tests/conftest.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/tests/test_account_commands.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/tests/test_account_enforcement.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/tests/test_auth_accounts.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/tests/test_auth_provider.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/tests/test_docs.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/tests/test_download_screening.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/tests/test_gmail_mime.py +0 -0
- {gws_cli-1.5.0 → gws_cli-1.6.0}/tests/test_output.py +0 -0
|
@@ -9,9 +9,9 @@ Manual testing of all CLI operations against real Google Workspace accounts.
|
|
|
9
9
|
| Metric | Count | Notes |
|
|
10
10
|
|--------|-------|-------|
|
|
11
11
|
| Pass | 210 | |
|
|
12
|
-
| Skip |
|
|
12
|
+
| Skip | 7 | Destructive or require external setup (e.g. target email, ownership transfer) |
|
|
13
13
|
| Expected fail | 1 | API correctly rejects the operation (e.g. unsubscribe from owned calendar) |
|
|
14
|
-
| **Total** | **
|
|
14
|
+
| **Total** | **218** | |
|
|
15
15
|
|
|
16
16
|
---
|
|
17
17
|
|
|
@@ -236,6 +236,7 @@ Manual testing of all CLI operations against real Google Workspace accounts.
|
|
|
236
236
|
| 215 | Convert |`convert md-to-doc /tmp/test.md -t "Title"`|PASS| 2026-02-06 |Markdown to Google Doc|
|
|
237
237
|
| 216 | Convert |`convert md-to-pdf /tmp/test.md /tmp/out.pdf`|PASS| 2026-02-06 |Markdown to PDF (35KB)|
|
|
238
238
|
| 217 | Convert |`convert md-to-slides /tmp/test.md -t "Title"`|PASS| 2026-02-06 |Markdown to Slides|
|
|
239
|
+
| 218 | Infra |`gws-cli auth --headless`|SKIP| 2026-10-14 |Needs interactive browser consent; covered by unit tests. Contributor-verified on a headless server|
|
|
239
240
|
|
|
240
241
|
---
|
|
241
242
|
|
|
@@ -273,3 +274,4 @@ Manual testing of all CLI operations against real Google Workspace accounts.
|
|
|
273
274
|
|------|-------------|
|
|
274
275
|
| 2026-02-05 | Initial test run: Infra, Drive, Docs, Sheets, Slides, Gmail. Fixed 10 bugs. |
|
|
275
276
|
| 2026-02-06 | Completed: Calendar, Contacts, Convert. Fixed 2 bugs (Slides). All 217 tests done. |
|
|
277
|
+
| 2026-10-14 | Added `auth --headless` (#218) from PR #1. Unit-tested (redirect validation, PKCE exchange, no secret echo); live test pending. |
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: gws-cli
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.6.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
|
|
@@ -24,7 +24,9 @@ Requires-Dist: google-api-python-client>=2.100.0
|
|
|
24
24
|
Requires-Dist: google-auth-oauthlib>=1.1.0
|
|
25
25
|
Requires-Dist: google-auth>=2.23.0
|
|
26
26
|
Requires-Dist: httpx>=0.25.0
|
|
27
|
+
Requires-Dist: oauthlib>=3.0.0
|
|
27
28
|
Requires-Dist: prompt-security-utils>=1.3.0
|
|
29
|
+
Requires-Dist: requests>=2.0.0
|
|
28
30
|
Requires-Dist: rich>=13.0.0
|
|
29
31
|
Requires-Dist: typer>=0.9.0
|
|
30
32
|
Provides-Extra: dev
|
|
@@ -32,6 +34,8 @@ Requires-Dist: mypy>=1.0.0; extra == 'dev'
|
|
|
32
34
|
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
|
|
33
35
|
Requires-Dist: pytest>=7.0.0; extra == 'dev'
|
|
34
36
|
Requires-Dist: ruff>=0.1.0; extra == 'dev'
|
|
37
|
+
Requires-Dist: types-oauthlib; extra == 'dev'
|
|
38
|
+
Requires-Dist: types-requests; extra == 'dev'
|
|
35
39
|
Description-Content-Type: text/markdown
|
|
36
40
|
|
|
37
41
|
# gws-cli — Google Workspace CLI & Claude Code Skill
|
|
@@ -115,10 +119,38 @@ All commands output JSON for easy scripting and integration.
|
|
|
115
119
|
```bash
|
|
116
120
|
# Opens browser for Google sign-in
|
|
117
121
|
uvx gws-cli auth
|
|
122
|
+
|
|
123
|
+
# Headless server: open the printed URL elsewhere, then paste the full redirect URL
|
|
124
|
+
uvx gws-cli auth --headless
|
|
125
|
+
|
|
126
|
+
# Headless + new named account: register it without auth, then authenticate
|
|
127
|
+
uvx gws-cli account add work --no-auth
|
|
128
|
+
uvx gws-cli auth --headless --account work
|
|
129
|
+
|
|
130
|
+
# Forced re-authentication is supported too
|
|
131
|
+
uvx gws-cli auth --headless --force --account work
|
|
118
132
|
```
|
|
119
133
|
|
|
120
134
|
That's it. Authentication is automatic on subsequent uses.
|
|
121
135
|
|
|
136
|
+
In local mode, `--headless` keeps Google's desktop-app loopback redirect and PKCE
|
|
137
|
+
protection; it does not use the deprecated OAuth out-of-band flow. After consent,
|
|
138
|
+
the browser's loopback page may fail to load. Copy the complete
|
|
139
|
+
`http://127.0.0.1:<port>/...` address from the browser bar and paste it into the
|
|
140
|
+
CLI. The pasted URL contains a one-time authorization code, so the CLI hides the
|
|
141
|
+
input and you should not log or share it. In server-relay mode, `--headless` uses
|
|
142
|
+
the relay's device flow for the initial server login, then prints the upstream
|
|
143
|
+
authorization URL and polls the relay; no loopback URL is pasted into the CLI.
|
|
144
|
+
|
|
145
|
+
On a headless machine, also set `GWS_HEADLESS=1` (for example in your shell
|
|
146
|
+
profile). It makes every login headless, including the automatic one a command
|
|
147
|
+
starts when it finds no token, or when a relay refresh finds no server session.
|
|
148
|
+
Without it, those automatic logins use the browser flow.
|
|
149
|
+
|
|
150
|
+
`--force` keeps your current token until the new login succeeds, so a cancelled
|
|
151
|
+
or failed re-authentication leaves you logged in. Run `gws-cli auth logout`
|
|
152
|
+
first if you also want the old token revoked.
|
|
153
|
+
|
|
122
154
|
## Using with AI Assistants
|
|
123
155
|
|
|
124
156
|
### Claude Code
|
|
@@ -79,10 +79,38 @@ All commands output JSON for easy scripting and integration.
|
|
|
79
79
|
```bash
|
|
80
80
|
# Opens browser for Google sign-in
|
|
81
81
|
uvx gws-cli auth
|
|
82
|
+
|
|
83
|
+
# Headless server: open the printed URL elsewhere, then paste the full redirect URL
|
|
84
|
+
uvx gws-cli auth --headless
|
|
85
|
+
|
|
86
|
+
# Headless + new named account: register it without auth, then authenticate
|
|
87
|
+
uvx gws-cli account add work --no-auth
|
|
88
|
+
uvx gws-cli auth --headless --account work
|
|
89
|
+
|
|
90
|
+
# Forced re-authentication is supported too
|
|
91
|
+
uvx gws-cli auth --headless --force --account work
|
|
82
92
|
```
|
|
83
93
|
|
|
84
94
|
That's it. Authentication is automatic on subsequent uses.
|
|
85
95
|
|
|
96
|
+
In local mode, `--headless` keeps Google's desktop-app loopback redirect and PKCE
|
|
97
|
+
protection; it does not use the deprecated OAuth out-of-band flow. After consent,
|
|
98
|
+
the browser's loopback page may fail to load. Copy the complete
|
|
99
|
+
`http://127.0.0.1:<port>/...` address from the browser bar and paste it into the
|
|
100
|
+
CLI. The pasted URL contains a one-time authorization code, so the CLI hides the
|
|
101
|
+
input and you should not log or share it. In server-relay mode, `--headless` uses
|
|
102
|
+
the relay's device flow for the initial server login, then prints the upstream
|
|
103
|
+
authorization URL and polls the relay; no loopback URL is pasted into the CLI.
|
|
104
|
+
|
|
105
|
+
On a headless machine, also set `GWS_HEADLESS=1` (for example in your shell
|
|
106
|
+
profile). It makes every login headless, including the automatic one a command
|
|
107
|
+
starts when it finds no token, or when a relay refresh finds no server session.
|
|
108
|
+
Without it, those automatic logins use the browser flow.
|
|
109
|
+
|
|
110
|
+
`--force` keeps your current token until the new login succeeds, so a cancelled
|
|
111
|
+
or failed re-authentication leaves you logged in. Run `gws-cli auth logout`
|
|
112
|
+
first if you also want the old token revoked.
|
|
113
|
+
|
|
86
114
|
## Using with AI Assistants
|
|
87
115
|
|
|
88
116
|
### Claude Code
|
|
@@ -325,12 +325,15 @@ All commands use `uvx gws-cli <service> <command>`. Authentication is automatic
|
|
|
325
325
|
|
|
326
326
|
## Authentication
|
|
327
327
|
|
|
328
|
-
> **Important**: `gws-cli auth`
|
|
328
|
+
> **Important**: `gws-cli auth` (including `--force` and `--headless`) must be run by the user in their own terminal, not from Claude Code. Normal mode opens a browser. On a headless server, use `--headless`: in local mode the user pastes the final loopback redirect URL into the CLI's hidden prompt; in server-relay mode it uses device login instead. That redirect URL contains a one-time authorization code, so **never ask the user to paste it into the chat**.
|
|
329
329
|
|
|
330
330
|
```bash
|
|
331
331
|
uvx gws-cli auth # Authenticate using the configured mode (opens browser)
|
|
332
|
+
uvx gws-cli auth --headless # No browser launch; paste the full redirect URL
|
|
332
333
|
uvx gws-cli auth status # Check auth status — reports the active mode
|
|
333
|
-
uvx gws-cli auth --force # Force re-authentication (
|
|
334
|
+
uvx gws-cli auth --force # Force re-authentication (current token kept until it succeeds)
|
|
335
|
+
uvx gws-cli auth --headless --force -a work # Headless named-account re-auth
|
|
336
|
+
export GWS_HEADLESS=1 # Headless machine: make every login headless, incl. automatic ones
|
|
334
337
|
uvx gws-cli auth logout # Logout (best-effort revokes the token upstream)
|
|
335
338
|
# Auth commands support --account for multi-account
|
|
336
339
|
uvx gws-cli auth status --account work
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
| `gws-cli --version` | ✅ Pass | Returns `{"version": "1.0.0"}` |
|
|
14
14
|
| `gws-cli --help` | ✅ Pass | Shows all commands |
|
|
15
15
|
| `gws-cli auth` | ✅ Pass | OAuth loopback flow works, token saved |
|
|
16
|
+
| `gws-cli auth --headless` | ✅ Unit | Browser suppressed; full redirect URL validated and exchanged with PKCE |
|
|
16
17
|
| `gws-cli auth status` | ✅ Pass | Non-interactive check works |
|
|
17
18
|
| `gws-cli auth logout` | ✅ Pass | Deletes token |
|
|
18
19
|
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "gws-cli"
|
|
7
|
-
version = "1.
|
|
7
|
+
version = "1.6.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"
|
|
@@ -31,6 +31,9 @@ dependencies = [
|
|
|
31
31
|
"google-api-python-client>=2.100.0",
|
|
32
32
|
"google-auth>=2.23.0",
|
|
33
33
|
"google-auth-oauthlib>=1.1.0",
|
|
34
|
+
# Imported directly by the headless OAuth flow; same bounds requests-oauthlib requires.
|
|
35
|
+
"oauthlib>=3.0.0",
|
|
36
|
+
"requests>=2.0.0",
|
|
34
37
|
"httpx>=0.25.0",
|
|
35
38
|
"prompt-security-utils>=1.3.0",
|
|
36
39
|
"cryptography>=46.0.4",
|
|
@@ -46,6 +49,8 @@ dev = [
|
|
|
46
49
|
"pytest-cov>=4.0.0",
|
|
47
50
|
"mypy>=1.0.0",
|
|
48
51
|
"ruff>=0.1.0",
|
|
52
|
+
"types-oauthlib",
|
|
53
|
+
"types-requests",
|
|
49
54
|
]
|
|
50
55
|
|
|
51
56
|
[project.scripts]
|
|
@@ -1,21 +1,90 @@
|
|
|
1
1
|
"""OAuth authentication with loopback redirect flow."""
|
|
2
2
|
|
|
3
3
|
import json
|
|
4
|
+
import secrets
|
|
4
5
|
import socket
|
|
5
6
|
import webbrowser
|
|
7
|
+
from getpass import getpass
|
|
6
8
|
from pathlib import Path
|
|
9
|
+
from urllib.parse import parse_qs, urlparse
|
|
7
10
|
|
|
8
11
|
import google.auth.exceptions
|
|
12
|
+
from google.auth.transport.requests import Request
|
|
9
13
|
from google.oauth2.credentials import Credentials
|
|
10
14
|
from google_auth_oauthlib.flow import InstalledAppFlow
|
|
11
|
-
from
|
|
15
|
+
from oauthlib.oauth2 import OAuth2Error
|
|
16
|
+
from requests.exceptions import RequestException
|
|
12
17
|
|
|
18
|
+
from gws.auth.provider import headless_requested
|
|
13
19
|
from gws.auth.scopes import get_scopes_for_services
|
|
14
20
|
from gws.config import Config
|
|
15
|
-
from gws.crypto import
|
|
21
|
+
from gws.crypto import delete_encrypted, load_encrypted, save_encrypted
|
|
16
22
|
from gws.exceptions import AuthError
|
|
17
23
|
|
|
18
24
|
|
|
25
|
+
def _validate_headless_redirect(
|
|
26
|
+
redirect_url: str,
|
|
27
|
+
expected_redirect_uri: str,
|
|
28
|
+
expected_state: str,
|
|
29
|
+
) -> None:
|
|
30
|
+
"""Validate a pasted loopback OAuth redirect before exchanging its code."""
|
|
31
|
+
if not redirect_url.strip():
|
|
32
|
+
raise AuthError("Headless authentication cancelled: no redirect URL was provided.")
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
parsed = urlparse(redirect_url.strip())
|
|
36
|
+
expected = urlparse(expected_redirect_uri)
|
|
37
|
+
redirect_matches = (
|
|
38
|
+
parsed.scheme == expected.scheme
|
|
39
|
+
and parsed.hostname == expected.hostname
|
|
40
|
+
and parsed.port == expected.port
|
|
41
|
+
and parsed.path == expected.path
|
|
42
|
+
and parsed.params == expected.params
|
|
43
|
+
and parsed.username is None
|
|
44
|
+
and parsed.password is None
|
|
45
|
+
)
|
|
46
|
+
except ValueError as exc:
|
|
47
|
+
raise AuthError("Invalid OAuth redirect URI") from exc
|
|
48
|
+
if not redirect_matches:
|
|
49
|
+
raise AuthError(
|
|
50
|
+
"Invalid OAuth redirect URI",
|
|
51
|
+
"Paste the complete loopback URL from the browser address bar.",
|
|
52
|
+
)
|
|
53
|
+
if parsed.fragment:
|
|
54
|
+
raise AuthError("Invalid OAuth redirect: URL fragments are not accepted.")
|
|
55
|
+
|
|
56
|
+
query = parse_qs(parsed.query, keep_blank_values=True)
|
|
57
|
+
states = query.get("state", [])
|
|
58
|
+
if len(states) != 1 or not secrets.compare_digest(states[0], expected_state):
|
|
59
|
+
raise AuthError("OAuth state validation failed.")
|
|
60
|
+
|
|
61
|
+
if "error" in query:
|
|
62
|
+
error = query["error"][0]
|
|
63
|
+
if error == "access_denied":
|
|
64
|
+
raise AuthError("Google authorization was denied.")
|
|
65
|
+
raise AuthError("Google authorization failed.")
|
|
66
|
+
|
|
67
|
+
codes = query.get("code", [])
|
|
68
|
+
if len(codes) != 1 or not codes[0]:
|
|
69
|
+
if len(codes) > 1:
|
|
70
|
+
raise AuthError("OAuth redirect must contain exactly one authorization code.")
|
|
71
|
+
raise AuthError("OAuth redirect is missing the authorization code.")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _fetch_headless_token(flow: InstalledAppFlow, redirect_url: str) -> None:
|
|
75
|
+
"""Exchange a validated loopback response without weakening OAuthlib globally.
|
|
76
|
+
|
|
77
|
+
OAuthlib rejects plain-HTTP authorization responses even for native-app
|
|
78
|
+
loopback redirects. ``InstalledAppFlow.run_local_server`` works around this
|
|
79
|
+
by changing only the response URL used for parsing to HTTPS while retaining
|
|
80
|
+
the original HTTP redirect URI in the token request. Mirror that behavior
|
|
81
|
+
for the manually pasted headless response.
|
|
82
|
+
"""
|
|
83
|
+
parsed = urlparse(redirect_url.strip())
|
|
84
|
+
authorization_response = parsed._replace(scheme="https").geturl()
|
|
85
|
+
flow.fetch_token(authorization_response=authorization_response)
|
|
86
|
+
|
|
87
|
+
|
|
19
88
|
class LocalAuthProvider:
|
|
20
89
|
"""Local OAuth authentication provider using client_secret.json.
|
|
21
90
|
|
|
@@ -63,8 +132,13 @@ class LocalAuthProvider:
|
|
|
63
132
|
return self.config.get_account_dir(self._account_name) / "token.json"
|
|
64
133
|
return self._LEGACY_TOKEN_PATH
|
|
65
134
|
|
|
66
|
-
def get_credentials(
|
|
135
|
+
def get_credentials(
|
|
136
|
+
self,
|
|
137
|
+
force_refresh: bool = False,
|
|
138
|
+
headless: bool = False,
|
|
139
|
+
) -> Credentials:
|
|
67
140
|
"""Get valid credentials, triggering auth flow if needed."""
|
|
141
|
+
headless = headless_requested(headless)
|
|
68
142
|
if self._credentials and self._credentials.valid and not force_refresh:
|
|
69
143
|
return self._credentials
|
|
70
144
|
|
|
@@ -90,14 +164,18 @@ class LocalAuthProvider:
|
|
|
90
164
|
self._credentials.refresh(Request())
|
|
91
165
|
self._save_credentials()
|
|
92
166
|
return self._credentials
|
|
93
|
-
except (
|
|
167
|
+
except (
|
|
168
|
+
google.auth.exceptions.RefreshError,
|
|
169
|
+
google.auth.exceptions.TransportError,
|
|
170
|
+
OSError,
|
|
171
|
+
) as e:
|
|
94
172
|
import sys
|
|
95
173
|
print(f"[gws-cli] Warning: token refresh failed: {e}", file=sys.stderr)
|
|
96
174
|
self._credentials = None
|
|
97
175
|
|
|
98
176
|
# Run auth flow if no valid credentials
|
|
99
177
|
if not self._credentials or not self._credentials.valid:
|
|
100
|
-
self._run_auth_flow(scopes)
|
|
178
|
+
self._run_auth_flow(scopes, headless=headless, consent=force_refresh)
|
|
101
179
|
|
|
102
180
|
return self._credentials # type: ignore
|
|
103
181
|
|
|
@@ -119,8 +197,16 @@ class LocalAuthProvider:
|
|
|
119
197
|
continue
|
|
120
198
|
raise AuthError("No available ports in range 8080-8099 for OAuth callback")
|
|
121
199
|
|
|
122
|
-
def _run_auth_flow(
|
|
123
|
-
|
|
200
|
+
def _run_auth_flow(
|
|
201
|
+
self,
|
|
202
|
+
scopes: list[str],
|
|
203
|
+
headless: bool = False,
|
|
204
|
+
consent: bool = False,
|
|
205
|
+
) -> None:
|
|
206
|
+
"""Run the OAuth loopback authentication flow.
|
|
207
|
+
|
|
208
|
+
consent: force Google's consent screen (used by `auth --force`).
|
|
209
|
+
"""
|
|
124
210
|
import sys
|
|
125
211
|
|
|
126
212
|
key = self.config.get_encryption_key()
|
|
@@ -132,37 +218,97 @@ class LocalAuthProvider:
|
|
|
132
218
|
)
|
|
133
219
|
|
|
134
220
|
port = self._find_available_port()
|
|
221
|
+
# A forced re-login keeps the old grant until it succeeds, and Google
|
|
222
|
+
# may then omit the refresh token; prompt=consent guarantees a new one.
|
|
223
|
+
auth_params = {"prompt": "consent"} if consent else {}
|
|
224
|
+
|
|
225
|
+
if headless:
|
|
226
|
+
# PKCE is what protects the pasted code. google-auth-oauthlib < 1.3
|
|
227
|
+
# only enables it when asked, so request it explicitly here; the
|
|
228
|
+
# browser flow below keeps the library default, as before.
|
|
229
|
+
flow = InstalledAppFlow.from_client_config(
|
|
230
|
+
client_config,
|
|
231
|
+
scopes=scopes,
|
|
232
|
+
autogenerate_code_verifier=True,
|
|
233
|
+
)
|
|
234
|
+
self._run_headless_auth_flow(flow, port, auth_params)
|
|
235
|
+
self._save_credentials()
|
|
236
|
+
return
|
|
135
237
|
|
|
136
238
|
flow = InstalledAppFlow.from_client_config(
|
|
137
239
|
client_config,
|
|
138
240
|
scopes=scopes,
|
|
139
241
|
)
|
|
140
242
|
|
|
141
|
-
# Try to open browser
|
|
142
243
|
try:
|
|
143
244
|
can_open_browser = webbrowser.get() is not None
|
|
144
245
|
except webbrowser.Error:
|
|
145
246
|
can_open_browser = False
|
|
146
247
|
|
|
147
|
-
# Print header
|
|
148
248
|
print("\n" + "=" * 60, file=sys.stderr)
|
|
149
249
|
account_label = f" (account: {self._account_name})" if self._account_name else ""
|
|
150
250
|
print(f"Google OAuth Authorization Required for gws-cli{account_label}", file=sys.stderr)
|
|
151
251
|
print("=" * 60, file=sys.stderr)
|
|
152
252
|
|
|
153
|
-
# Let run_local_server handle everything including URL generation
|
|
154
|
-
# The authorization_prompt_message will print the URL
|
|
155
253
|
self._credentials = flow.run_local_server(
|
|
156
254
|
host=self.LOOPBACK_IP,
|
|
157
255
|
port=port,
|
|
158
256
|
open_browser=can_open_browser,
|
|
159
|
-
authorization_prompt_message=
|
|
257
|
+
authorization_prompt_message=(
|
|
258
|
+
"\n{url}\n\n" + "=" * 60 + "\nWaiting for authorization...\n"
|
|
259
|
+
),
|
|
160
260
|
success_message="Authorization successful! You can close this window.",
|
|
261
|
+
**auth_params,
|
|
161
262
|
)
|
|
162
263
|
|
|
163
264
|
print("\n✓ Authorization successful! Token saved.\n", file=sys.stderr)
|
|
164
265
|
self._save_credentials()
|
|
165
266
|
|
|
267
|
+
def _run_headless_auth_flow(
|
|
268
|
+
self,
|
|
269
|
+
flow: InstalledAppFlow,
|
|
270
|
+
port: int,
|
|
271
|
+
auth_params: dict[str, str] | None = None,
|
|
272
|
+
) -> None:
|
|
273
|
+
"""Complete local OAuth without a browser or callback HTTP server."""
|
|
274
|
+
import sys
|
|
275
|
+
|
|
276
|
+
redirect_uri = f"http://{self.LOOPBACK_IP}:{port}/"
|
|
277
|
+
flow.redirect_uri = redirect_uri
|
|
278
|
+
authorization_url, state = flow.authorization_url(**(auth_params or {}))
|
|
279
|
+
|
|
280
|
+
print("\n" + "=" * 60, file=sys.stderr)
|
|
281
|
+
account_label = f" (account: {self._account_name})" if self._account_name else ""
|
|
282
|
+
print(f"Google OAuth Headless Authorization for gws-cli{account_label}", file=sys.stderr)
|
|
283
|
+
print("=" * 60, file=sys.stderr)
|
|
284
|
+
print("\n1. Open this URL in a browser on another computer:\n", file=sys.stderr)
|
|
285
|
+
print(authorization_url, file=sys.stderr)
|
|
286
|
+
print(
|
|
287
|
+
"\n2. Complete Google sign-in and consent. The final loopback page may fail to load."
|
|
288
|
+
"\n3. Copy the ENTIRE URL from the browser address bar and paste it below."
|
|
289
|
+
"\n Treat that URL as a one-time secret; do not share or log it.\n",
|
|
290
|
+
file=sys.stderr,
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
try:
|
|
294
|
+
redirect_url = getpass("Full redirect URL (input hidden): ", stream=sys.stderr).strip()
|
|
295
|
+
except (EOFError, KeyboardInterrupt) as exc:
|
|
296
|
+
raise AuthError("Headless authentication cancelled.") from exc
|
|
297
|
+
|
|
298
|
+
_validate_headless_redirect(redirect_url, redirect_uri, state)
|
|
299
|
+
try:
|
|
300
|
+
_fetch_headless_token(flow, redirect_url)
|
|
301
|
+
except (OAuth2Error, ValueError, OSError, RequestException) as exc:
|
|
302
|
+
raise AuthError(
|
|
303
|
+
"Failed to exchange the OAuth authorization code.",
|
|
304
|
+
"The code may be expired or already used. Run the command again.",
|
|
305
|
+
) from exc
|
|
306
|
+
|
|
307
|
+
self._credentials = flow.credentials
|
|
308
|
+
if not self._credentials or not self._credentials.valid:
|
|
309
|
+
raise AuthError("Google returned invalid OAuth credentials.")
|
|
310
|
+
print("\nAuthorization successful! Token saved.\n", file=sys.stderr)
|
|
311
|
+
|
|
166
312
|
def _save_credentials(self) -> None:
|
|
167
313
|
"""Save credentials to token file (encrypted if enabled)."""
|
|
168
314
|
if self._credentials:
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import os
|
|
5
6
|
from pathlib import Path
|
|
6
7
|
from typing import Any, Protocol, runtime_checkable
|
|
7
8
|
from urllib.parse import urlparse
|
|
@@ -17,7 +18,11 @@ class AuthProvider(Protocol):
|
|
|
17
18
|
ServerAuthProvider: delegates to an oauth-token-relay server.
|
|
18
19
|
"""
|
|
19
20
|
|
|
20
|
-
def get_credentials(
|
|
21
|
+
def get_credentials(
|
|
22
|
+
self,
|
|
23
|
+
force_refresh: bool = False,
|
|
24
|
+
headless: bool = False,
|
|
25
|
+
) -> Credentials:
|
|
21
26
|
"""Get valid Google API credentials, triggering auth if needed."""
|
|
22
27
|
...
|
|
23
28
|
|
|
@@ -44,6 +49,17 @@ class AuthProvider(Protocol):
|
|
|
44
49
|
...
|
|
45
50
|
|
|
46
51
|
|
|
52
|
+
def headless_requested(explicit: bool = False) -> bool:
|
|
53
|
+
"""Whether to use headless auth flows: the --headless flag or GWS_HEADLESS.
|
|
54
|
+
|
|
55
|
+
GWS_HEADLESS (1/true/yes/on) also covers implicit logins — a command that
|
|
56
|
+
finds no token, or a relay refresh that finds no server session — which
|
|
57
|
+
would otherwise wait for a browser callback that can never arrive.
|
|
58
|
+
"""
|
|
59
|
+
value = os.environ.get("GWS_HEADLESS", "").strip().lower()
|
|
60
|
+
return explicit or value in {"1", "true", "yes", "on"}
|
|
61
|
+
|
|
62
|
+
|
|
47
63
|
def _validate_server_url(url: str) -> None:
|
|
48
64
|
"""Require HTTPS for non-localhost relay server URLs."""
|
|
49
65
|
from gws.exceptions import AuthError
|
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import base64
|
|
5
6
|
import hashlib
|
|
6
7
|
import json
|
|
7
8
|
import secrets
|
|
8
|
-
import base64
|
|
9
9
|
import sys
|
|
10
10
|
import time
|
|
11
11
|
import webbrowser
|
|
@@ -16,11 +16,11 @@ from urllib.parse import urlencode, urlparse
|
|
|
16
16
|
import httpx
|
|
17
17
|
from google.oauth2.credentials import Credentials
|
|
18
18
|
|
|
19
|
+
from gws.auth.provider import headless_requested
|
|
19
20
|
from gws.config import Config
|
|
20
|
-
from gws.crypto import
|
|
21
|
+
from gws.crypto import delete_encrypted, load_encrypted, save_encrypted
|
|
21
22
|
from gws.exceptions import AuthError
|
|
22
23
|
|
|
23
|
-
|
|
24
24
|
# Recognised Google OAuth consent hosts the relay may legitimately return.
|
|
25
25
|
_KNOWN_AUTH_HOSTS = {"accounts.google.com"}
|
|
26
26
|
|
|
@@ -118,7 +118,11 @@ class ServerAuthProvider:
|
|
|
118
118
|
|
|
119
119
|
# ── AuthProvider protocol methods ─────────────────────────────────
|
|
120
120
|
|
|
121
|
-
def get_credentials(
|
|
121
|
+
def get_credentials(
|
|
122
|
+
self,
|
|
123
|
+
force_refresh: bool = False,
|
|
124
|
+
headless: bool = False,
|
|
125
|
+
) -> Credentials:
|
|
122
126
|
"""Get valid Google API credentials via the server relay.
|
|
123
127
|
|
|
124
128
|
Flow:
|
|
@@ -128,6 +132,7 @@ class ServerAuthProvider:
|
|
|
128
132
|
4. If no credentials, initiate full flow via server
|
|
129
133
|
5. Save credentials locally
|
|
130
134
|
"""
|
|
135
|
+
headless = headless_requested(headless)
|
|
131
136
|
if self._credentials and self._credentials.valid and not force_refresh:
|
|
132
137
|
return self._credentials
|
|
133
138
|
|
|
@@ -138,16 +143,22 @@ class ServerAuthProvider:
|
|
|
138
143
|
# Refresh if expired
|
|
139
144
|
if self._credentials and self._credentials.expired and self._credentials.refresh_token:
|
|
140
145
|
try:
|
|
141
|
-
self._refresh_via_server(self._credentials.refresh_token)
|
|
146
|
+
self._refresh_via_server(self._credentials.refresh_token, headless=headless)
|
|
142
147
|
return self._credentials # Set by _refresh_via_server
|
|
143
|
-
except (
|
|
148
|
+
except (
|
|
149
|
+
httpx.RequestError,
|
|
150
|
+
httpx.HTTPStatusError,
|
|
151
|
+
AuthError,
|
|
152
|
+
json.JSONDecodeError,
|
|
153
|
+
KeyError,
|
|
154
|
+
) as e:
|
|
144
155
|
import sys
|
|
145
156
|
print(f"[gws-cli] Warning: server token refresh failed: {e}", file=sys.stderr)
|
|
146
157
|
self._credentials = None
|
|
147
158
|
|
|
148
159
|
# Full flow: start → browser → complete
|
|
149
160
|
if not self._credentials or not self._credentials.valid:
|
|
150
|
-
self._run_server_auth_flow()
|
|
161
|
+
self._run_server_auth_flow(headless=headless)
|
|
151
162
|
|
|
152
163
|
return self._credentials # type: ignore[return-value]
|
|
153
164
|
|
|
@@ -392,7 +403,7 @@ class ServerAuthProvider:
|
|
|
392
403
|
|
|
393
404
|
# ── Private: Google token relay ───────────────────────────────────
|
|
394
405
|
|
|
395
|
-
def _run_server_auth_flow(self) -> None:
|
|
406
|
+
def _run_server_auth_flow(self, headless: bool = False) -> None:
|
|
396
407
|
"""Initiate upstream OAuth via the server relay.
|
|
397
408
|
|
|
398
409
|
The CLI sends full scope URLs directly — the server is scope-agnostic
|
|
@@ -400,7 +411,7 @@ class ServerAuthProvider:
|
|
|
400
411
|
"""
|
|
401
412
|
from gws.auth.scopes import get_scopes_for_services
|
|
402
413
|
|
|
403
|
-
server_token = self._ensure_server_token()
|
|
414
|
+
server_token = self._ensure_server_token(headless=headless)
|
|
404
415
|
scopes = get_scopes_for_services(
|
|
405
416
|
self.config.enabled_services,
|
|
406
417
|
read_only=self.config.read_only,
|
|
@@ -438,7 +449,7 @@ class ServerAuthProvider:
|
|
|
438
449
|
except webbrowser.Error:
|
|
439
450
|
can_open = False
|
|
440
451
|
|
|
441
|
-
if can_open:
|
|
452
|
+
if can_open and not headless:
|
|
442
453
|
print(f"\nOpening browser to:\n{auth_url}\n", file=sys.stderr)
|
|
443
454
|
webbrowser.open(auth_url)
|
|
444
455
|
else:
|
|
@@ -474,9 +485,12 @@ class ServerAuthProvider:
|
|
|
474
485
|
|
|
475
486
|
raise AuthError("Authorization timed out. Please try again.")
|
|
476
487
|
|
|
477
|
-
def _refresh_via_server(self, refresh_token: str) -> None:
|
|
478
|
-
"""Refresh Google API token via the server relay.
|
|
479
|
-
|
|
488
|
+
def _refresh_via_server(self, refresh_token: str, headless: bool = False) -> None:
|
|
489
|
+
"""Refresh Google API token via the server relay.
|
|
490
|
+
|
|
491
|
+
headless: if the relay session is missing, log in with device flow.
|
|
492
|
+
"""
|
|
493
|
+
server_token = self._ensure_server_token(headless=headless)
|
|
480
494
|
|
|
481
495
|
resp = self._server_request(
|
|
482
496
|
"POST",
|
|
@@ -618,7 +632,11 @@ class ServerAuthProvider:
|
|
|
618
632
|
save_encrypted(self._server_token_path, token_data, self.config.get_encryption_key())
|
|
619
633
|
self._server_token = token_data
|
|
620
634
|
|
|
621
|
-
def _ensure_server_token(
|
|
635
|
+
def _ensure_server_token(
|
|
636
|
+
self,
|
|
637
|
+
auto_login: bool = True,
|
|
638
|
+
headless: bool = False,
|
|
639
|
+
) -> dict[str, Any]:
|
|
622
640
|
"""Load server token, auto-triggering login if needed.
|
|
623
641
|
|
|
624
642
|
When auto_login is True (the default), missing server tokens trigger
|
|
@@ -637,7 +655,7 @@ class ServerAuthProvider:
|
|
|
637
655
|
|
|
638
656
|
# Auto-trigger server login — one fewer manual step for the user
|
|
639
657
|
print("No server token found — starting server authentication...\n", file=sys.stderr)
|
|
640
|
-
self.server_login()
|
|
658
|
+
self.server_login(device_flow=headless)
|
|
641
659
|
|
|
642
660
|
token = self._load_server_token()
|
|
643
661
|
if not token:
|