brewsorted-cli 0.8.4__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.
- brewsorted_cli/__init__.py +5 -0
- brewsorted_cli/_skill/SKILL.md +201 -0
- brewsorted_cli/_skill/__init__.py +1 -0
- brewsorted_cli/_skill/agents/openai.yaml +6 -0
- brewsorted_cli/_skill/references/cli.md +471 -0
- brewsorted_cli/_skill/tests/acceptance_scenarios.json +946 -0
- brewsorted_cli/_skill/tests/test_skill.py +534 -0
- brewsorted_cli/auth_state.py +273 -0
- brewsorted_cli/client.py +482 -0
- brewsorted_cli/http.py +29 -0
- brewsorted_cli/main.py +851 -0
- brewsorted_cli/oauth_discovery.py +120 -0
- brewsorted_cli/oauth_login.py +277 -0
- brewsorted_cli/product_feedback.py +114 -0
- brewsorted_cli/skills.py +45 -0
- brewsorted_cli/updates.py +76 -0
- brewsorted_cli-0.8.4.dist-info/METADATA +172 -0
- brewsorted_cli-0.8.4.dist-info/RECORD +21 -0
- brewsorted_cli-0.8.4.dist-info/WHEEL +5 -0
- brewsorted_cli-0.8.4.dist-info/entry_points.txt +2 -0
- brewsorted_cli-0.8.4.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Exact-origin Keycloak discovery and CLI token validation."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
import jwt
|
|
10
|
+
from jwt import PyJWKClient
|
|
11
|
+
|
|
12
|
+
from . import USER_AGENT
|
|
13
|
+
from .http import http_client
|
|
14
|
+
from .auth_state import AuthStateError, IssuerUnavailable
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class IssuerMetadata:
|
|
19
|
+
issuer: str
|
|
20
|
+
authorization_endpoint: str
|
|
21
|
+
token_endpoint: str
|
|
22
|
+
device_authorization_endpoint: str
|
|
23
|
+
revocation_endpoint: str
|
|
24
|
+
jwks_uri: str
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def expected_issuer(service_origin: str) -> str:
|
|
28
|
+
return f"{service_origin}/id/realms/brewsorted"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _exact_endpoints(issuer: str) -> dict[str, str]:
|
|
32
|
+
protocol = f"{issuer}/protocol/openid-connect"
|
|
33
|
+
return {
|
|
34
|
+
"authorization_endpoint": f"{protocol}/auth",
|
|
35
|
+
"token_endpoint": f"{protocol}/token",
|
|
36
|
+
"device_authorization_endpoint": f"{protocol}/auth/device",
|
|
37
|
+
"revocation_endpoint": f"{protocol}/revoke",
|
|
38
|
+
"jwks_uri": f"{protocol}/certs",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def discover(service_origin: str, *, client: httpx.Client | None = None,
|
|
43
|
+
proxy: str | None = None) -> IssuerMetadata:
|
|
44
|
+
issuer = expected_issuer(service_origin)
|
|
45
|
+
endpoint = f"{issuer}/.well-known/openid-configuration"
|
|
46
|
+
own_client = client is None
|
|
47
|
+
transport = client or http_client(proxy=proxy)
|
|
48
|
+
try:
|
|
49
|
+
try:
|
|
50
|
+
response = transport.get(endpoint, headers={"User-Agent": USER_AGENT})
|
|
51
|
+
except httpx.RequestError as exc:
|
|
52
|
+
raise IssuerUnavailable("Issuer discovery is unavailable") from exc
|
|
53
|
+
finally:
|
|
54
|
+
if own_client:
|
|
55
|
+
transport.close()
|
|
56
|
+
if response.status_code != 200 or response.headers.get("content-type", "").split(";", 1)[0] != "application/json":
|
|
57
|
+
raise IssuerUnavailable("Issuer discovery returned an invalid response")
|
|
58
|
+
try:
|
|
59
|
+
metadata = response.json()
|
|
60
|
+
except ValueError as exc:
|
|
61
|
+
raise IssuerUnavailable("Issuer discovery returned invalid JSON") from exc
|
|
62
|
+
expected = _exact_endpoints(issuer)
|
|
63
|
+
if (
|
|
64
|
+
not isinstance(metadata, dict) or metadata.get("issuer") != issuer
|
|
65
|
+
or any(metadata.get(name) != value for name, value in expected.items())
|
|
66
|
+
or "S256" not in metadata.get("code_challenge_methods_supported", [])
|
|
67
|
+
):
|
|
68
|
+
raise AuthStateError("Issuer metadata does not match the selected service")
|
|
69
|
+
return IssuerMetadata(issuer=issuer, **expected)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class _SigningKeyClient(PyJWKClient):
|
|
73
|
+
"""Use the same proxy/TLS policy for keys as for the rest of OAuth."""
|
|
74
|
+
|
|
75
|
+
def __init__(self, uri: str, *, proxy: str | None = None):
|
|
76
|
+
super().__init__(uri, cache_jwk_set=True, lifespan=300, timeout=5,
|
|
77
|
+
headers={"User-Agent": USER_AGENT})
|
|
78
|
+
self.proxy = proxy
|
|
79
|
+
|
|
80
|
+
def fetch_data(self) -> Any:
|
|
81
|
+
try:
|
|
82
|
+
with http_client(proxy=self.proxy, timeout=self.timeout) as client:
|
|
83
|
+
response = client.get(self.uri, headers=self.headers)
|
|
84
|
+
response.raise_for_status()
|
|
85
|
+
data = response.json()
|
|
86
|
+
except (httpx.HTTPError, ValueError) as exc:
|
|
87
|
+
raise jwt.PyJWKClientConnectionError("Signing keys are unavailable") from exc
|
|
88
|
+
if self.jwk_set_cache is not None:
|
|
89
|
+
self.jwk_set_cache.put(data)
|
|
90
|
+
self._last_successful_fetch = time.monotonic()
|
|
91
|
+
return data
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class AccessTokenVerifier:
|
|
95
|
+
def __init__(self, metadata: IssuerMetadata, *, jwks_client: PyJWKClient | None = None,
|
|
96
|
+
proxy: str | None = None):
|
|
97
|
+
self.metadata = metadata
|
|
98
|
+
self.jwks_client = jwks_client or _SigningKeyClient(metadata.jwks_uri, proxy=proxy)
|
|
99
|
+
|
|
100
|
+
def verify(self, token: str, *, expected_subject: str | None = None) -> dict[str, Any]:
|
|
101
|
+
try:
|
|
102
|
+
key = self.jwks_client.get_signing_key_from_jwt(token)
|
|
103
|
+
claims = jwt.decode(
|
|
104
|
+
token, key.key, algorithms=["RS256"], audience="brewsorted-api",
|
|
105
|
+
issuer=self.metadata.issuer,
|
|
106
|
+
options={"require": ["iss", "sub", "aud", "exp", "iat", "azp"]},
|
|
107
|
+
)
|
|
108
|
+
except (jwt.PyJWTError, OSError, ValueError) as exc:
|
|
109
|
+
raise AuthStateError("Issuer credential validation failed") from exc
|
|
110
|
+
if (
|
|
111
|
+
claims.get("azp") != "brewsorted-cli"
|
|
112
|
+
or claims.get("typ") not in ("Bearer", "at+jwt")
|
|
113
|
+
or not isinstance(claims.get("sub"), str) or not claims["sub"]
|
|
114
|
+
or type(claims.get("iat")) is not int
|
|
115
|
+
or type(claims.get("exp")) is not int
|
|
116
|
+
or claims["exp"] - claims["iat"] > 300
|
|
117
|
+
or (expected_subject is not None and claims["sub"] != expected_subject)
|
|
118
|
+
):
|
|
119
|
+
raise AuthStateError("Issuer credential validation failed")
|
|
120
|
+
return claims
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"""Deliberate public-client OAuth login using stock Keycloak endpoints."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import hashlib
|
|
6
|
+
import secrets
|
|
7
|
+
import socket
|
|
8
|
+
import time
|
|
9
|
+
import webbrowser
|
|
10
|
+
from typing import Callable
|
|
11
|
+
from urllib.parse import parse_qs, urlencode, urlsplit
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from . import USER_AGENT
|
|
16
|
+
from .http import http_client
|
|
17
|
+
|
|
18
|
+
from .auth_state import AuthBinding, AuthState, AuthStateError, IssuerUnavailable
|
|
19
|
+
from .oauth_discovery import AccessTokenVerifier, IssuerMetadata, discover
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class LoginDenied(AuthStateError):
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _url_safe(value: bytes) -> str:
|
|
27
|
+
return base64.urlsafe_b64encode(value).rstrip(b"=").decode("ascii")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class OAuthLogin:
|
|
31
|
+
def __init__(
|
|
32
|
+
self, service_origin: str, state: AuthState, *,
|
|
33
|
+
client: httpx.Client | None = None, proxy: str | None = None,
|
|
34
|
+
verifier_factory: Callable[[IssuerMetadata], AccessTokenVerifier] | None = None,
|
|
35
|
+
progress: Callable[[str], None] = print,
|
|
36
|
+
) -> None:
|
|
37
|
+
self.service_origin = service_origin
|
|
38
|
+
self.state = state
|
|
39
|
+
self.client = client
|
|
40
|
+
self.proxy = proxy
|
|
41
|
+
self.verifier_factory = verifier_factory or (
|
|
42
|
+
lambda metadata: AccessTokenVerifier(metadata, proxy=proxy)
|
|
43
|
+
)
|
|
44
|
+
self.progress = progress
|
|
45
|
+
|
|
46
|
+
def _client(self) -> httpx.Client:
|
|
47
|
+
return self.client or http_client(proxy=self.proxy)
|
|
48
|
+
|
|
49
|
+
def _token_response(self, client: httpx.Client, metadata: IssuerMetadata, form: dict[str, str]) -> dict:
|
|
50
|
+
try:
|
|
51
|
+
response = client.post(metadata.token_endpoint, data=form,
|
|
52
|
+
headers={"User-Agent": USER_AGENT})
|
|
53
|
+
except httpx.RequestError as exc:
|
|
54
|
+
raise IssuerUnavailable("Issuer token service is unavailable") from exc
|
|
55
|
+
if response.status_code in (400, 401):
|
|
56
|
+
raise LoginDenied("Authorization was denied or expired; run login again")
|
|
57
|
+
if response.status_code != 200 or response.headers.get("content-type", "").split(";", 1)[0] != "application/json":
|
|
58
|
+
raise IssuerUnavailable("Issuer token response is invalid")
|
|
59
|
+
try:
|
|
60
|
+
result = response.json()
|
|
61
|
+
except ValueError as exc:
|
|
62
|
+
raise AuthStateError("Issuer token response is invalid") from exc
|
|
63
|
+
if not isinstance(result, dict):
|
|
64
|
+
raise AuthStateError("Issuer token response is invalid")
|
|
65
|
+
return result
|
|
66
|
+
|
|
67
|
+
def _revoke(self, client: httpx.Client, metadata: IssuerMetadata, refresh: str) -> None:
|
|
68
|
+
try:
|
|
69
|
+
client.post(metadata.revocation_endpoint, data={
|
|
70
|
+
"client_id": "brewsorted-cli", "token": refresh,
|
|
71
|
+
"token_type_hint": "refresh_token",
|
|
72
|
+
}, headers={"User-Agent": USER_AGENT})
|
|
73
|
+
except httpx.RequestError:
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
def _finish(self, client: httpx.Client, metadata: IssuerMetadata, tokens: dict) -> dict[str, str]:
|
|
77
|
+
if not isinstance(tokens, dict):
|
|
78
|
+
raise AuthStateError("Issuer token response is incomplete")
|
|
79
|
+
access = tokens.get("access_token")
|
|
80
|
+
refresh = tokens.get("refresh_token")
|
|
81
|
+
expires = tokens.get("expires_in")
|
|
82
|
+
if (
|
|
83
|
+
not isinstance(access, str) or not access
|
|
84
|
+
or not isinstance(refresh, str) or not refresh
|
|
85
|
+
or type(expires) is not int or not 1 <= expires <= 300
|
|
86
|
+
or tokens.get("token_type", "Bearer").lower() != "bearer"
|
|
87
|
+
):
|
|
88
|
+
if isinstance(refresh, str) and refresh:
|
|
89
|
+
self._revoke(client, metadata, refresh)
|
|
90
|
+
raise AuthStateError("Issuer token response is incomplete")
|
|
91
|
+
try:
|
|
92
|
+
claims = self.verifier_factory(metadata).verify(access)
|
|
93
|
+
try:
|
|
94
|
+
me = client.get(
|
|
95
|
+
f"{self.service_origin}/api/v1/auth/me",
|
|
96
|
+
headers={"Authorization": f"Bearer {access}", "User-Agent": USER_AGENT},
|
|
97
|
+
)
|
|
98
|
+
except httpx.RequestError as exc:
|
|
99
|
+
raise IssuerUnavailable("BrewSorted could not verify the authorized User") from exc
|
|
100
|
+
if me.status_code != 200 or me.headers.get("content-type", "").split(";", 1)[0] != "application/json":
|
|
101
|
+
raise AuthStateError("BrewSorted did not accept the authorized User")
|
|
102
|
+
try:
|
|
103
|
+
user = me.json()
|
|
104
|
+
except ValueError as exc:
|
|
105
|
+
raise AuthStateError("BrewSorted User response is invalid") from exc
|
|
106
|
+
if (
|
|
107
|
+
not isinstance(user, dict) or user.get("state") != "active"
|
|
108
|
+
or user.get("credential_kind") != "oauth-agent"
|
|
109
|
+
or not isinstance(user.get("username"), str)
|
|
110
|
+
or not user["username"]
|
|
111
|
+
):
|
|
112
|
+
raise AuthStateError("BrewSorted User response is invalid")
|
|
113
|
+
binding = AuthBinding(
|
|
114
|
+
format_version=1, service_origin=self.service_origin,
|
|
115
|
+
issuer=metadata.issuer, subject=claims["sub"],
|
|
116
|
+
username=user["username"], audience="brewsorted-api",
|
|
117
|
+
client_id="brewsorted-cli", token_endpoint=metadata.token_endpoint,
|
|
118
|
+
revocation_endpoint=metadata.revocation_endpoint,
|
|
119
|
+
access_token=access, refresh_token=refresh,
|
|
120
|
+
expires_at=int(claims["exp"]),
|
|
121
|
+
)
|
|
122
|
+
self.state.save_new(binding)
|
|
123
|
+
except Exception:
|
|
124
|
+
self._revoke(client, metadata, refresh)
|
|
125
|
+
raise
|
|
126
|
+
return {"service_origin": self.service_origin, "username": user["username"], "connected": "yes"}
|
|
127
|
+
|
|
128
|
+
def device(self) -> dict[str, str]:
|
|
129
|
+
own_client = self.client is None
|
|
130
|
+
client = self._client()
|
|
131
|
+
try:
|
|
132
|
+
metadata = discover(self.service_origin, client=client)
|
|
133
|
+
verifier = _url_safe(secrets.token_bytes(32))
|
|
134
|
+
challenge = _url_safe(hashlib.sha256(verifier.encode("ascii")).digest())
|
|
135
|
+
try:
|
|
136
|
+
response = client.post(metadata.device_authorization_endpoint, data={
|
|
137
|
+
"client_id": "brewsorted-cli", "scope": "openid offline_access",
|
|
138
|
+
"code_challenge_method": "S256", "code_challenge": challenge,
|
|
139
|
+
}, headers={"User-Agent": USER_AGENT})
|
|
140
|
+
except httpx.RequestError as exc:
|
|
141
|
+
raise IssuerUnavailable("Device authorization is unavailable") from exc
|
|
142
|
+
if response.status_code != 200 or response.headers.get("content-type", "").split(";", 1)[0] != "application/json":
|
|
143
|
+
raise IssuerUnavailable("Device authorization response is invalid")
|
|
144
|
+
try:
|
|
145
|
+
device = response.json()
|
|
146
|
+
except ValueError as exc:
|
|
147
|
+
raise AuthStateError("Device authorization response is invalid") from exc
|
|
148
|
+
if not isinstance(device, dict):
|
|
149
|
+
raise AuthStateError("Device authorization response is invalid")
|
|
150
|
+
verification_url = device.get("verification_uri")
|
|
151
|
+
code = device.get("user_code")
|
|
152
|
+
device_code = device.get("device_code")
|
|
153
|
+
lifetime = device.get("expires_in")
|
|
154
|
+
interval = device.get("interval", 5)
|
|
155
|
+
if (
|
|
156
|
+
not isinstance(verification_url, str)
|
|
157
|
+
or verification_url != f"{metadata.issuer}/device"
|
|
158
|
+
or not isinstance(code, str) or not code
|
|
159
|
+
or not isinstance(device_code, str) or not device_code
|
|
160
|
+
or type(lifetime) is not int or not 1 <= lifetime <= 600
|
|
161
|
+
or type(interval) is not int or not 1 <= interval <= 30
|
|
162
|
+
):
|
|
163
|
+
raise AuthStateError("Device authorization response is invalid")
|
|
164
|
+
complete_url = device.get("verification_uri_complete")
|
|
165
|
+
if complete_url is not None:
|
|
166
|
+
if not isinstance(complete_url, str) or any(
|
|
167
|
+
ord(character) <= 32 or ord(character) == 127
|
|
168
|
+
for character in complete_url
|
|
169
|
+
):
|
|
170
|
+
raise AuthStateError("Device verification URL is invalid")
|
|
171
|
+
try:
|
|
172
|
+
complete = urlsplit(complete_url)
|
|
173
|
+
expected = urlsplit(verification_url)
|
|
174
|
+
query = parse_qs(complete.query, keep_blank_values=True)
|
|
175
|
+
except ValueError as exc:
|
|
176
|
+
raise AuthStateError("Device verification URL is invalid") from exc
|
|
177
|
+
if (
|
|
178
|
+
(complete.scheme, complete.netloc, complete.path)
|
|
179
|
+
!= (expected.scheme, expected.netloc, expected.path)
|
|
180
|
+
or complete.fragment or query != {"user_code": [code]}
|
|
181
|
+
):
|
|
182
|
+
raise AuthStateError("Device verification URL is invalid")
|
|
183
|
+
self.progress(f"Visit {complete_url} and confirm code {code}")
|
|
184
|
+
else:
|
|
185
|
+
self.progress(f"Visit {verification_url} and enter code {code}")
|
|
186
|
+
deadline = time.monotonic() + lifetime
|
|
187
|
+
while time.monotonic() < deadline:
|
|
188
|
+
time.sleep(interval)
|
|
189
|
+
try:
|
|
190
|
+
token_response = client.post(metadata.token_endpoint, data={
|
|
191
|
+
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
|
|
192
|
+
"client_id": "brewsorted-cli", "device_code": device_code,
|
|
193
|
+
"code_verifier": verifier,
|
|
194
|
+
}, headers={"User-Agent": USER_AGENT})
|
|
195
|
+
except httpx.RequestError as exc:
|
|
196
|
+
raise IssuerUnavailable("Issuer token service is unavailable") from exc
|
|
197
|
+
if token_response.status_code == 400:
|
|
198
|
+
try:
|
|
199
|
+
error = token_response.json().get("error")
|
|
200
|
+
except (ValueError, AttributeError):
|
|
201
|
+
raise AuthStateError("Device authorization response is invalid") from None
|
|
202
|
+
if error == "authorization_pending":
|
|
203
|
+
continue
|
|
204
|
+
if error == "slow_down":
|
|
205
|
+
interval = min(interval + 5, 30)
|
|
206
|
+
continue
|
|
207
|
+
raise LoginDenied("Device authorization was denied or expired")
|
|
208
|
+
if token_response.status_code != 200 or token_response.headers.get("content-type", "").split(";", 1)[0] != "application/json":
|
|
209
|
+
raise IssuerUnavailable("Issuer token response is invalid")
|
|
210
|
+
try:
|
|
211
|
+
tokens = token_response.json()
|
|
212
|
+
except ValueError as exc:
|
|
213
|
+
raise AuthStateError("Issuer token response is invalid") from exc
|
|
214
|
+
return self._finish(client, metadata, tokens)
|
|
215
|
+
raise LoginDenied("Device authorization expired; run login again")
|
|
216
|
+
finally:
|
|
217
|
+
if own_client:
|
|
218
|
+
client.close()
|
|
219
|
+
|
|
220
|
+
def loopback(self, *, open_browser: bool = False, timeout: int = 120) -> dict[str, str]:
|
|
221
|
+
own_client = self.client is None
|
|
222
|
+
client = self._client()
|
|
223
|
+
try:
|
|
224
|
+
metadata = discover(self.service_origin, client=client)
|
|
225
|
+
verifier = _url_safe(secrets.token_bytes(32))
|
|
226
|
+
challenge = _url_safe(hashlib.sha256(verifier.encode("ascii")).digest())
|
|
227
|
+
state = _url_safe(secrets.token_bytes(32))
|
|
228
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
|
|
229
|
+
listener.bind(("127.0.0.1", 0))
|
|
230
|
+
listener.listen(1)
|
|
231
|
+
listener.settimeout(timeout)
|
|
232
|
+
redirect_uri = f"http://127.0.0.1:{listener.getsockname()[1]}/oauth/callback"
|
|
233
|
+
authorization_url = f"{metadata.authorization_endpoint}?" + urlencode({
|
|
234
|
+
"response_type": "code", "client_id": "brewsorted-cli",
|
|
235
|
+
"redirect_uri": redirect_uri, "scope": "openid offline_access",
|
|
236
|
+
"state": state, "code_challenge": challenge,
|
|
237
|
+
"code_challenge_method": "S256",
|
|
238
|
+
})
|
|
239
|
+
self.progress(f"Open this sign-in URL: {authorization_url}")
|
|
240
|
+
if open_browser:
|
|
241
|
+
webbrowser.open(authorization_url)
|
|
242
|
+
try:
|
|
243
|
+
connection, _ = listener.accept()
|
|
244
|
+
except socket.timeout as exc:
|
|
245
|
+
raise LoginDenied("Login timed out; run login again") from exc
|
|
246
|
+
with connection:
|
|
247
|
+
connection.settimeout(5)
|
|
248
|
+
request_line = connection.recv(4096).split(b"\r\n", 1)[0]
|
|
249
|
+
try:
|
|
250
|
+
method, target, _ = request_line.decode("ascii").split(" ", 2)
|
|
251
|
+
except (UnicodeError, ValueError):
|
|
252
|
+
raise LoginDenied("OAuth callback is invalid") from None
|
|
253
|
+
parsed = urlsplit(target)
|
|
254
|
+
fields = parse_qs(parsed.query, strict_parsing=True)
|
|
255
|
+
valid = (
|
|
256
|
+
method == "GET" and parsed.path == "/oauth/callback"
|
|
257
|
+
and fields.get("state") == [state]
|
|
258
|
+
and len(fields.get("code", [])) == 1
|
|
259
|
+
and len(fields["code"][0]) <= 2048
|
|
260
|
+
)
|
|
261
|
+
page = b"BrewSorted sign-in received. Return to your terminal." if valid else b"BrewSorted sign-in was not accepted."
|
|
262
|
+
connection.sendall(
|
|
263
|
+
b"HTTP/1.1 " + (b"200 OK" if valid else b"400 Bad Request")
|
|
264
|
+
+ b"\r\nContent-Type: text/plain\r\nCache-Control: no-store\r\n"
|
|
265
|
+
+ f"Content-Length: {len(page)}\r\nConnection: close\r\n\r\n".encode("ascii") + page
|
|
266
|
+
)
|
|
267
|
+
if not valid:
|
|
268
|
+
raise LoginDenied("OAuth callback is invalid or denied")
|
|
269
|
+
code = fields["code"][0]
|
|
270
|
+
tokens = self._token_response(client, metadata, {
|
|
271
|
+
"grant_type": "authorization_code", "client_id": "brewsorted-cli",
|
|
272
|
+
"code": code, "redirect_uri": redirect_uri, "code_verifier": verifier,
|
|
273
|
+
})
|
|
274
|
+
return self._finish(client, metadata, tokens)
|
|
275
|
+
finally:
|
|
276
|
+
if own_client:
|
|
277
|
+
client.close()
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Receipt-only Product feedback contract owned by the CLI."""
|
|
2
|
+
import json
|
|
3
|
+
from uuid import UUID
|
|
4
|
+
|
|
5
|
+
from .client import ApiError
|
|
6
|
+
|
|
7
|
+
UNCERTAIN = (
|
|
8
|
+
"Delivery is uncertain. Submit again only if you accept a possible duplicate."
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def strict_json(raw):
|
|
13
|
+
def pairs(items):
|
|
14
|
+
value = {}
|
|
15
|
+
for key, item in items:
|
|
16
|
+
if key in value:
|
|
17
|
+
raise ValueError("Duplicate JSON property")
|
|
18
|
+
value[key] = item
|
|
19
|
+
return value
|
|
20
|
+
|
|
21
|
+
def constant(_value):
|
|
22
|
+
raise ValueError("Invalid JSON constant")
|
|
23
|
+
|
|
24
|
+
return json.loads(raw, object_pairs_hook=pairs, parse_constant=constant)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def validate_submission(value):
|
|
28
|
+
if not isinstance(value, dict) or set(value) != {"message"}:
|
|
29
|
+
raise ValueError("Product feedback requires exactly one message")
|
|
30
|
+
text = value["message"]
|
|
31
|
+
if (
|
|
32
|
+
type(text) is not str
|
|
33
|
+
or not 1 <= len(text) <= 10000
|
|
34
|
+
or not text.strip()
|
|
35
|
+
or any(c == "\0" or 0xD800 <= ord(c) <= 0xDFFF for c in text)
|
|
36
|
+
):
|
|
37
|
+
raise ValueError("Product feedback requires 1–10,000 valid text characters")
|
|
38
|
+
return value
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def failure(status=504, code="feedback_delivery_uncertain", retry_after=None):
|
|
42
|
+
detail = {
|
|
43
|
+
"feedback_delivery_uncertain": UNCERTAIN,
|
|
44
|
+
"feedback_unavailable": "Product feedback is temporarily unavailable.",
|
|
45
|
+
"feedback_rate_limited": "Please wait before submitting more Product feedback.",
|
|
46
|
+
"authentication_required": "Sign in before submitting Product feedback.",
|
|
47
|
+
"capability_denied": "This Connection or User state cannot submit Product feedback.",
|
|
48
|
+
}.get(code, "Product feedback was rejected.")
|
|
49
|
+
body = {
|
|
50
|
+
"type": "about:blank",
|
|
51
|
+
"title": "Product feedback",
|
|
52
|
+
"status": status,
|
|
53
|
+
"detail": detail,
|
|
54
|
+
"code": code,
|
|
55
|
+
}
|
|
56
|
+
if retry_after is not None:
|
|
57
|
+
body["retry_after"] = retry_after
|
|
58
|
+
return ApiError(status, body)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def decode_response(status, headers, raw):
|
|
62
|
+
try:
|
|
63
|
+
kind = headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
|
64
|
+
payload = strict_json(raw.decode("utf-8"))
|
|
65
|
+
if status == 201 and kind == "application/json":
|
|
66
|
+
if (
|
|
67
|
+
not isinstance(payload, dict)
|
|
68
|
+
or set(payload) != {"report_id", "status"}
|
|
69
|
+
or payload["status"] != "received"
|
|
70
|
+
or type(payload["report_id"]) is not str
|
|
71
|
+
):
|
|
72
|
+
raise ValueError
|
|
73
|
+
parsed = UUID(payload["report_id"])
|
|
74
|
+
if parsed.version != 4 or str(parsed) != payload["report_id"]:
|
|
75
|
+
raise ValueError
|
|
76
|
+
return payload
|
|
77
|
+
if (
|
|
78
|
+
kind != "application/problem+json"
|
|
79
|
+
or not isinstance(payload, dict)
|
|
80
|
+
or type(payload.get("status")) is not int
|
|
81
|
+
or payload["status"] != status
|
|
82
|
+
or any(
|
|
83
|
+
type(payload.get(k)) is not str
|
|
84
|
+
for k in ("type", "title", "detail", "code")
|
|
85
|
+
)
|
|
86
|
+
):
|
|
87
|
+
raise ValueError
|
|
88
|
+
code = payload["code"]
|
|
89
|
+
allowed = {
|
|
90
|
+
401: {"authentication_required"},
|
|
91
|
+
403: {"capability_denied", "origin_rejected", "proxy_rejected"},
|
|
92
|
+
413: {"feedback_payload_too_large"},
|
|
93
|
+
415: {"unsupported_media_type"},
|
|
94
|
+
422: {"validation_error"},
|
|
95
|
+
429: {"feedback_rate_limited"},
|
|
96
|
+
503: {"feedback_unavailable", "maintenance_required", "storage_pressure"},
|
|
97
|
+
504: {"feedback_delivery_uncertain"},
|
|
98
|
+
}
|
|
99
|
+
if code not in allowed.get(status, set()):
|
|
100
|
+
raise ValueError
|
|
101
|
+
retry = None
|
|
102
|
+
if status == 429:
|
|
103
|
+
text = headers.get("retry-after", "")
|
|
104
|
+
if (
|
|
105
|
+
not text.isascii()
|
|
106
|
+
or not text.isdecimal()
|
|
107
|
+
or not 1 <= len(text) <= 6
|
|
108
|
+
or int(text) < 1
|
|
109
|
+
):
|
|
110
|
+
raise ValueError
|
|
111
|
+
retry = int(text)
|
|
112
|
+
except (ValueError, UnicodeError, RecursionError):
|
|
113
|
+
raise failure() from None
|
|
114
|
+
raise failure(status, code, retry)
|
brewsorted_cli/skills.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Install the complete skill shipped with this executable, without network access."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
from importlib.resources import files
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import shutil
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
|
|
12
|
+
# Keep this list explicit: every installed file belongs to the reviewed User skill.
|
|
13
|
+
SKILL_FILES = (
|
|
14
|
+
"SKILL.md", "references/cli.md", "agents/openai.yaml",
|
|
15
|
+
"tests/acceptance_scenarios.json", "tests/test_skill.py",
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def install_skill(destination: Path) -> dict:
|
|
20
|
+
destination = destination.expanduser().absolute()
|
|
21
|
+
source = files("brewsorted_cli._skill")
|
|
22
|
+
contents = {name: source.joinpath(name).read_bytes() for name in SKILL_FILES}
|
|
23
|
+
receipt = {
|
|
24
|
+
"cli_version": __version__,
|
|
25
|
+
"files": {name: hashlib.sha256(data).hexdigest() for name, data in contents.items()},
|
|
26
|
+
}
|
|
27
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
28
|
+
try:
|
|
29
|
+
destination.mkdir(mode=0o700)
|
|
30
|
+
except FileExistsError:
|
|
31
|
+
raise ValueError(
|
|
32
|
+
f"Skill destination already exists: {destination}; inspect and move it before installing"
|
|
33
|
+
) from None
|
|
34
|
+
try:
|
|
35
|
+
for name, content in contents.items():
|
|
36
|
+
path = destination / name
|
|
37
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
38
|
+
path.write_bytes(content)
|
|
39
|
+
(destination / "brewsorted-install.json").write_text(
|
|
40
|
+
json.dumps(receipt, indent=2) + "\n", encoding="utf-8"
|
|
41
|
+
)
|
|
42
|
+
except OSError:
|
|
43
|
+
shutil.rmtree(destination)
|
|
44
|
+
raise
|
|
45
|
+
return {"skill": "brewsorted", "cli_version": __version__, "destination": str(destination)}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Advisory update checks and installation-local reminder claims."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import fcntl
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
import stat
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
from . import __version__
|
|
13
|
+
from .client import ApiClient, ApiError, BackendUnavailable, InvalidServerResponse
|
|
14
|
+
|
|
15
|
+
VERSION = re.compile(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def check_updates(client: ApiClient) -> dict:
|
|
19
|
+
result = {"current_version": __version__, "recommended_version": None,
|
|
20
|
+
"update_available": None}
|
|
21
|
+
try:
|
|
22
|
+
metadata = client.request(
|
|
23
|
+
"GET", "/api/capabilities", response_kind="capabilities", authenticate=False,
|
|
24
|
+
)
|
|
25
|
+
except (ApiError, BackendUnavailable, InvalidServerResponse):
|
|
26
|
+
return result
|
|
27
|
+
recommended = metadata["recommended_client_bundle_version"]
|
|
28
|
+
current_match = VERSION.fullmatch(__version__)
|
|
29
|
+
recommended_match = VERSION.fullmatch(recommended)
|
|
30
|
+
if current_match is not None and recommended_match is not None:
|
|
31
|
+
result.update(
|
|
32
|
+
recommended_version=recommended,
|
|
33
|
+
update_available=(tuple((len(part), part) for part in recommended_match.groups())
|
|
34
|
+
> tuple((len(part), part) for part in current_match.groups())),
|
|
35
|
+
)
|
|
36
|
+
return result
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def update_message(result: dict) -> str | None:
|
|
40
|
+
if result["update_available"]:
|
|
41
|
+
return f"Client bundle {result['recommended_version']} is available."
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def claim_reminder(state_path: Path, *, now: float | None = None) -> bool:
|
|
46
|
+
"""Reserve a reminder, failing quiet when durable suppression is unavailable."""
|
|
47
|
+
timestamp = time.time() if now is None else now
|
|
48
|
+
path = state_path.with_name(state_path.name + ".update-reminder")
|
|
49
|
+
try:
|
|
50
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
51
|
+
parent = path.parent.lstat()
|
|
52
|
+
if (not stat.S_ISDIR(parent.st_mode) or parent.st_uid != os.getuid()
|
|
53
|
+
or parent.st_mode & 0o077):
|
|
54
|
+
return False
|
|
55
|
+
descriptor = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
|
|
56
|
+
with os.fdopen(descriptor, "r+", encoding="ascii") as stream:
|
|
57
|
+
info = os.fstat(stream.fileno())
|
|
58
|
+
if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid()
|
|
59
|
+
or info.st_mode & 0o077 or info.st_nlink != 1):
|
|
60
|
+
return False
|
|
61
|
+
fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
62
|
+
stored = stream.read(129)
|
|
63
|
+
if len(stored) > 128:
|
|
64
|
+
return False
|
|
65
|
+
if stored:
|
|
66
|
+
previous = float(stored)
|
|
67
|
+
if not math.isfinite(previous) or timestamp - previous < 86400:
|
|
68
|
+
return False
|
|
69
|
+
stream.seek(0)
|
|
70
|
+
stream.write(str(timestamp) + "\n")
|
|
71
|
+
stream.truncate()
|
|
72
|
+
stream.flush()
|
|
73
|
+
os.fsync(stream.fileno())
|
|
74
|
+
return True
|
|
75
|
+
except (OSError, ValueError, UnicodeError):
|
|
76
|
+
return False
|