hoja-cli 0.21.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.
Files changed (107) hide show
  1. VERSION +1 -0
  2. google_workspace/__init__.py +19 -0
  3. google_workspace/client.py +253 -0
  4. google_workspace/config.py +39 -0
  5. google_workspace/errors.py +19 -0
  6. google_workspace/mcp_server.py +100 -0
  7. google_workspace/oauth.py +131 -0
  8. google_workspace/principal.py +83 -0
  9. google_workspace/py.typed +0 -0
  10. google_workspace/tools.py +64 -0
  11. google_workspace/writes.py +44 -0
  12. hoja/__init__.py +29 -0
  13. hoja/__main__.py +6 -0
  14. hoja/auth.py +42 -0
  15. hoja/cli.py +161 -0
  16. hoja/cli_state.py +55 -0
  17. hoja/client.py +268 -0
  18. hoja/commands/__init__.py +4 -0
  19. hoja/commands/auth_cmd.py +271 -0
  20. hoja/commands/comment.py +149 -0
  21. hoja/commands/cycle.py +75 -0
  22. hoja/commands/init.py +108 -0
  23. hoja/commands/issue.py +398 -0
  24. hoja/commands/label.py +163 -0
  25. hoja/commands/memory.py +240 -0
  26. hoja/commands/project.py +56 -0
  27. hoja/commands/raw.py +50 -0
  28. hoja/commands/team.py +102 -0
  29. hoja/commands/update.py +162 -0
  30. hoja/config.py +362 -0
  31. hoja/errors.py +107 -0
  32. hoja/filters.py +150 -0
  33. hoja/graphql/__init__.py +5 -0
  34. hoja/graphql/fragments.py +138 -0
  35. hoja/graphql/mutations.py +160 -0
  36. hoja/graphql/queries.py +245 -0
  37. hoja/mcp/__init__.py +27 -0
  38. hoja/mcp/content.py +151 -0
  39. hoja/mcp/prompts.py +298 -0
  40. hoja/mcp/resources.py +213 -0
  41. hoja/mcp/server.py +189 -0
  42. hoja/memory_board.py +370 -0
  43. hoja/models/__init__.py +37 -0
  44. hoja/models/base.py +64 -0
  45. hoja/models/cycle.py +32 -0
  46. hoja/models/enums.py +62 -0
  47. hoja/models/issue.py +99 -0
  48. hoja/models/label.py +17 -0
  49. hoja/models/project.py +60 -0
  50. hoja/models/team.py +31 -0
  51. hoja/models/user.py +32 -0
  52. hoja/models/workflow.py +65 -0
  53. hoja/output.py +410 -0
  54. hoja/skill_content/commands.md +222 -0
  55. hoja/skill_content/examples.md +193 -0
  56. hoja/skill_content/filters.md +101 -0
  57. hoja/skill_content/output-formats.md +92 -0
  58. hoja/skill_content/overview.md +123 -0
  59. hoja/skill_content/workflows.md +174 -0
  60. hoja_cli-0.21.4.dist-info/METADATA +279 -0
  61. hoja_cli-0.21.4.dist-info/RECORD +107 -0
  62. hoja_cli-0.21.4.dist-info/WHEEL +4 -0
  63. hoja_cli-0.21.4.dist-info/entry_points.txt +4 -0
  64. hoja_cli-0.21.4.dist-info/licenses/LICENSE +21 -0
  65. hoja_server/README.md +135 -0
  66. hoja_server/__init__.py +11 -0
  67. hoja_server/abac.py +116 -0
  68. hoja_server/agent_chat.py +280 -0
  69. hoja_server/agent_conversations.py +91 -0
  70. hoja_server/agent_durable.py +332 -0
  71. hoja_server/agent_prompt.py +117 -0
  72. hoja_server/agent_threads.py +96 -0
  73. hoja_server/agent_uploads.py +60 -0
  74. hoja_server/app.py +2189 -0
  75. hoja_server/cadence.py +231 -0
  76. hoja_server/cli.py +191 -0
  77. hoja_server/cloudflare_realtime.py +110 -0
  78. hoja_server/comment_policy.py +70 -0
  79. hoja_server/connector_actions.py +119 -0
  80. hoja_server/connectors_api.py +375 -0
  81. hoja_server/db.py +1816 -0
  82. hoja_server/denials.py +18 -0
  83. hoja_server/deployment.py +28 -0
  84. hoja_server/email_adapter.py +94 -0
  85. hoja_server/google_login.py +217 -0
  86. hoja_server/google_oidc.py +342 -0
  87. hoja_server/identity_transfer.py +210 -0
  88. hoja_server/mcp_oauth.py +623 -0
  89. hoja_server/mcp_tools.py +579 -0
  90. hoja_server/meeting_policy.py +179 -0
  91. hoja_server/meetings.py +1332 -0
  92. hoja_server/meetings_api.py +909 -0
  93. hoja_server/model_providers.py +205 -0
  94. hoja_server/realtime.py +690 -0
  95. hoja_server/resolvers.py +1281 -0
  96. hoja_server/schema.graphql +477 -0
  97. hoja_server/schema_sdl.py +8 -0
  98. hoja_server/secrets_box.py +39 -0
  99. hoja_server/signup_config.py +292 -0
  100. hoja_server/signup_gate.py +393 -0
  101. hoja_server/signup_policy.py +97 -0
  102. hoja_server/signup_store.py +577 -0
  103. hoja_server/store.py +2179 -0
  104. hoja_server/sync.py +249 -0
  105. hoja_server/tenant_context.py +131 -0
  106. hoja_server/turnstile.py +81 -0
  107. hoja_server/writer.py +1262 -0
@@ -0,0 +1,342 @@
1
+ """Google OIDC: authorization-code flow with PKCE S256, and strict ID-token checks.
2
+
3
+ Everything here is deliberately boring and explicit. The two rules that matter:
4
+
5
+ * **Only RS256 is accepted.** ``alg: none`` and every HMAC algorithm are
6
+ refused by name, before any key lookup, because those are the two ways a JWT
7
+ validator is historically confused into trusting attacker-chosen bytes.
8
+ * **A token is valid only if every claim is right**: ``iss``, ``aud``, ``exp``,
9
+ ``iat``, ``nonce`` and ``email_verified`` — the last one because the whole
10
+ point of the identity layer is that the address was proven.
11
+
12
+ Network calls are two module-level seams (:func:`get_jwks` and
13
+ :func:`exchange_code`, both built on :func:`_http_post_form`) so tests can drive
14
+ the flow without a socket.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import base64
20
+ import hashlib
21
+ import json
22
+ import secrets
23
+ import time
24
+ from dataclasses import dataclass
25
+ from typing import Any
26
+ from urllib.parse import urlencode
27
+
28
+ GOOGLE_AUTHORIZE_ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth"
29
+ GOOGLE_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
30
+ GOOGLE_JWKS_URI = "https://www.googleapis.com/oauth2/v3/certs"
31
+
32
+ #: Google mints both spellings in the wild; both name Google and nothing else.
33
+ GOOGLE_ISSUERS = frozenset({"https://accounts.google.com", "accounts.google.com"})
34
+
35
+ #: The only signature algorithm this deployment will accept.
36
+ ALLOWED_ALGORITHMS = frozenset({"RS256"})
37
+
38
+ #: Claims Google sends; a token missing any of these is not one of ours.
39
+ REQUIRED_CLAIMS = ("iss", "aud", "sub", "exp", "iat")
40
+
41
+ DEFAULT_LEEWAY_SECONDS = 120
42
+ JWKS_TTL_SECONDS = 3600
43
+ SCOPE = "openid email profile"
44
+
45
+
46
+ class OIDCError(ValueError):
47
+ """A token, exchange or state value was refused. ``reason`` is stable."""
48
+
49
+ def __init__(self, reason: str, message: str):
50
+ super().__init__(message)
51
+ self.reason = reason
52
+
53
+
54
+ # --------------------------------------------------------------------------- #
55
+ # base64url helpers
56
+ # --------------------------------------------------------------------------- #
57
+
58
+
59
+ def b64url_encode(raw: bytes) -> str:
60
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
61
+
62
+
63
+ def b64url_decode(segment: str) -> bytes:
64
+ if not isinstance(segment, str) or not segment:
65
+ raise OIDCError("malformed", "Empty base64url segment.")
66
+ if any(ch not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="
67
+ for ch in segment):
68
+ raise OIDCError("malformed", "Segment is not base64url.")
69
+ try:
70
+ return base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4))
71
+ except (ValueError, TypeError) as exc:
72
+ raise OIDCError("malformed", "Segment is not valid base64url.") from exc
73
+
74
+
75
+ def _json_object(raw: bytes, what: str) -> dict[str, Any]:
76
+ try:
77
+ value = json.loads(raw.decode("utf-8"))
78
+ except (ValueError, UnicodeDecodeError) as exc:
79
+ raise OIDCError("malformed", f"{what} is not JSON.") from exc
80
+ if not isinstance(value, dict):
81
+ raise OIDCError("malformed", f"{what} is not a JSON object.")
82
+ return value
83
+
84
+
85
+ # --------------------------------------------------------------------------- #
86
+ # PKCE and the authorization request
87
+ # --------------------------------------------------------------------------- #
88
+
89
+
90
+ def pkce_pair() -> tuple[str, str]:
91
+ """Return ``(code_verifier, code_challenge)`` for PKCE S256."""
92
+ verifier = secrets.token_urlsafe(48) # 64 chars, inside RFC 7636's 43..128
93
+ challenge = b64url_encode(hashlib.sha256(verifier.encode("ascii")).digest())
94
+ return verifier, challenge
95
+
96
+
97
+ def new_secret() -> str:
98
+ """32 bytes of URL-safe randomness, for state, nonce and the flow binding."""
99
+ return secrets.token_urlsafe(32)
100
+
101
+
102
+ def authorization_url(
103
+ *,
104
+ client_id: str,
105
+ redirect_uri: str,
106
+ state: str,
107
+ nonce: str,
108
+ code_challenge: str,
109
+ hosted_domain: str | None = None,
110
+ prompt: str | None = None,
111
+ endpoint: str = GOOGLE_AUTHORIZE_ENDPOINT,
112
+ ) -> str:
113
+ """The 302 target. No token ever comes back in a URL fragment (code flow)."""
114
+ if not code_challenge:
115
+ raise OIDCError("pkce_missing", "PKCE is mandatory.")
116
+ params = {
117
+ "response_type": "code",
118
+ "client_id": client_id,
119
+ "redirect_uri": redirect_uri,
120
+ "scope": SCOPE,
121
+ "state": state,
122
+ "nonce": nonce,
123
+ "code_challenge": code_challenge,
124
+ "code_challenge_method": "S256",
125
+ }
126
+ if hosted_domain:
127
+ params["hd"] = hosted_domain # a hint for the chooser, never a check
128
+ if prompt:
129
+ params["prompt"] = prompt
130
+ return f"{endpoint}?{urlencode(params)}"
131
+
132
+
133
+ # --------------------------------------------------------------------------- #
134
+ # JWKS
135
+ # --------------------------------------------------------------------------- #
136
+
137
+
138
+ @dataclass(frozen=True)
139
+ class Jwks:
140
+ """Google's signing keys, keyed by ``kid``. Only RSA signature keys are kept."""
141
+
142
+ keys: dict[str, Any]
143
+
144
+ @classmethod
145
+ def from_document(cls, document: dict[str, Any]) -> Jwks:
146
+ from cryptography.hazmat.primitives.asymmetric import rsa
147
+
148
+ raw_keys = document.get("keys") if isinstance(document, dict) else None
149
+ if not isinstance(raw_keys, list):
150
+ raise OIDCError("jwks_malformed", "JWKS document has no 'keys' list.")
151
+ keys: dict[str, Any] = {}
152
+ for entry in raw_keys:
153
+ if not isinstance(entry, dict):
154
+ continue
155
+ if entry.get("kty") != "RSA" or entry.get("use", "sig") != "sig":
156
+ continue
157
+ kid, modulus, exponent = entry.get("kid"), entry.get("n"), entry.get("e")
158
+ if not (isinstance(kid, str) and isinstance(modulus, str) and isinstance(exponent, str)):
159
+ continue
160
+ try:
161
+ numbers = rsa.RSAPublicNumbers(
162
+ int.from_bytes(b64url_decode(exponent), "big"),
163
+ int.from_bytes(b64url_decode(modulus), "big"),
164
+ )
165
+ keys[kid] = numbers.public_key()
166
+ except (OIDCError, ValueError):
167
+ continue
168
+ if not keys:
169
+ raise OIDCError("jwks_malformed", "JWKS document has no usable RSA key.")
170
+ return cls(keys=keys)
171
+
172
+ def verify(self, kid: str | None, signing_input: bytes, signature: bytes) -> None:
173
+ from cryptography.exceptions import InvalidSignature
174
+ from cryptography.hazmat.primitives import hashes
175
+ from cryptography.hazmat.primitives.asymmetric import padding
176
+
177
+ if not kid:
178
+ raise OIDCError("unknown_key", "ID token header has no 'kid'.")
179
+ key = self.keys.get(kid)
180
+ if key is None:
181
+ raise OIDCError("unknown_key", f"No JWKS key for kid {kid!r}.")
182
+ try:
183
+ key.verify(signature, signing_input, padding.PKCS1v15(), hashes.SHA256())
184
+ except InvalidSignature as exc:
185
+ raise OIDCError("bad_signature", "ID token signature does not verify.") from exc
186
+
187
+
188
+ _JWKS_CACHE: dict[str, tuple[float, Jwks]] = {}
189
+
190
+
191
+ def clear_jwks_cache() -> None:
192
+ _JWKS_CACHE.clear()
193
+
194
+
195
+ def _http_get_json(url: str, *, timeout: float = 5.0) -> dict[str, Any]:
196
+ """The single outbound GET seam. Tests replace it; production uses httpx."""
197
+ import httpx
198
+
199
+ response = httpx.get(url, timeout=timeout)
200
+ response.raise_for_status()
201
+ document = response.json()
202
+ if not isinstance(document, dict):
203
+ raise OIDCError("jwks_malformed", "JWKS response is not a JSON object.")
204
+ return document
205
+
206
+
207
+ def get_jwks(uri: str = GOOGLE_JWKS_URI, *, ttl: int = JWKS_TTL_SECONDS) -> Jwks:
208
+ """Fetch (and briefly cache) Google's keys. One GET per hour, not per login."""
209
+ now = time.monotonic()
210
+ cached = _JWKS_CACHE.get(uri)
211
+ if cached is not None and now - cached[0] < ttl:
212
+ return cached[1]
213
+ keys = Jwks.from_document(_http_get_json(uri))
214
+ _JWKS_CACHE[uri] = (now, keys)
215
+ return keys
216
+
217
+
218
+ # --------------------------------------------------------------------------- #
219
+ # ID token validation
220
+ # --------------------------------------------------------------------------- #
221
+
222
+
223
+ def _check_alg(header: dict[str, Any]) -> None:
224
+ alg = header.get("alg")
225
+ if not isinstance(alg, str) or not alg:
226
+ raise OIDCError("alg_missing", "ID token header has no 'alg'.")
227
+ if alg.lower() == "none":
228
+ raise OIDCError("alg_none", "Unsigned tokens (alg=none) are refused.")
229
+ if alg not in ALLOWED_ALGORITHMS:
230
+ raise OIDCError("alg_not_allowed", f"Signing algorithm {alg!r} is not allowed.")
231
+
232
+
233
+ def verify_id_token(
234
+ token: str,
235
+ *,
236
+ jwks: Jwks,
237
+ client_id: str,
238
+ nonce: str,
239
+ now: float | None = None,
240
+ leeway: int = DEFAULT_LEEWAY_SECONDS,
241
+ ) -> dict[str, Any]:
242
+ """Return the validated claims, or raise :class:`OIDCError`.
243
+
244
+ The order matters: header/alg first (no key material touched), signature
245
+ second, claims third.
246
+ """
247
+ if not isinstance(token, str) or token.count(".") != 2:
248
+ raise OIDCError("malformed", "ID token is not a compact JWS with three parts.")
249
+ header_b64, payload_b64, signature_b64 = token.split(".")
250
+ header = _json_object(b64url_decode(header_b64), "ID token header")
251
+ _check_alg(header)
252
+ if header.get("typ") not in (None, "JWT"):
253
+ raise OIDCError("malformed", "ID token header 'typ' is not JWT.")
254
+
255
+ signing_input = f"{header_b64}.{payload_b64}".encode("ascii")
256
+ jwks.verify(header.get("kid"), signing_input, b64url_decode(signature_b64))
257
+
258
+ claims = _json_object(b64url_decode(payload_b64), "ID token payload")
259
+ for claim in REQUIRED_CLAIMS:
260
+ if claim not in claims:
261
+ raise OIDCError("claim_missing", f"ID token has no {claim!r} claim.")
262
+
263
+ if claims["iss"] not in GOOGLE_ISSUERS:
264
+ raise OIDCError("issuer_mismatch", f"Unexpected issuer {claims['iss']!r}.")
265
+
266
+ audience = claims["aud"]
267
+ if isinstance(audience, list):
268
+ if client_id not in audience:
269
+ raise OIDCError("audience_mismatch", "Token audience does not include this client.")
270
+ if len(audience) > 1 and claims.get("azp") != client_id:
271
+ raise OIDCError("audience_mismatch", "Multi-audience token without a matching azp.")
272
+ elif audience != client_id:
273
+ raise OIDCError("audience_mismatch", "Token audience is another client.")
274
+
275
+ current = time.time() if now is None else float(now)
276
+ try:
277
+ expires = float(claims["exp"])
278
+ issued = float(claims["iat"])
279
+ except (TypeError, ValueError) as exc:
280
+ raise OIDCError("malformed", "exp/iat are not numeric.") from exc
281
+ if expires <= current - leeway:
282
+ raise OIDCError("token_expired", "ID token has expired.")
283
+ if issued > current + leeway:
284
+ raise OIDCError("token_not_yet_valid", "ID token was issued in the future.")
285
+
286
+ if not isinstance(nonce, str) or not nonce or claims.get("nonce") != nonce:
287
+ raise OIDCError("nonce_mismatch", "ID token nonce does not match this flow.")
288
+
289
+ if claims.get("email_verified") is not True:
290
+ raise OIDCError("email_unverified", "The Google account's email is not verified.")
291
+
292
+ subject = claims.get("sub")
293
+ if not isinstance(subject, str) or not subject.strip():
294
+ raise OIDCError("subject_missing", "ID token has no usable 'sub'.")
295
+ return claims
296
+
297
+
298
+ # --------------------------------------------------------------------------- #
299
+ # Code exchange
300
+ # --------------------------------------------------------------------------- #
301
+
302
+
303
+ def _http_post_form(url: str, data: dict[str, str], *, timeout: float = 10.0) -> dict[str, Any]:
304
+ """The single outbound POST seam. Tests replace it."""
305
+ import httpx
306
+
307
+ response = httpx.post(url, data=data, timeout=timeout)
308
+ try:
309
+ document = response.json()
310
+ except ValueError as exc:
311
+ raise OIDCError("exchange_failed", "Token endpoint returned non-JSON.") from exc
312
+ if not isinstance(document, dict):
313
+ raise OIDCError("exchange_failed", "Token endpoint returned a non-object.")
314
+ return document
315
+
316
+
317
+ def exchange_code(
318
+ *,
319
+ code: str,
320
+ code_verifier: str,
321
+ client_id: str,
322
+ client_secret: str,
323
+ redirect_uri: str,
324
+ endpoint: str = GOOGLE_TOKEN_ENDPOINT,
325
+ ) -> dict[str, Any]:
326
+ """Redeem the authorization code, bound to the PKCE verifier and redirect URI."""
327
+ document = _http_post_form(
328
+ endpoint,
329
+ {
330
+ "grant_type": "authorization_code",
331
+ "code": code,
332
+ "code_verifier": code_verifier,
333
+ "client_id": client_id,
334
+ "client_secret": client_secret,
335
+ "redirect_uri": redirect_uri,
336
+ },
337
+ )
338
+ if document.get("error"):
339
+ raise OIDCError("exchange_failed", str(document.get("error_description") or document["error"]))
340
+ if not document.get("id_token"):
341
+ raise OIDCError("exchange_failed", "Token response has no id_token.")
342
+ return document
@@ -0,0 +1,210 @@
1
+ """Hand a verified Google identity from the control plane to a tenant origin.
2
+
3
+ Google does not accept wildcard redirect URIs, so a per-tenant origin cannot
4
+ own its own OAuth client redirect. The control plane therefore completes the
5
+ code exchange exactly once, at the single registered redirect, and hands the
6
+ *already verified* claims to the tenant through a short-lived signed token.
7
+ The tenant redeems that token on its own host and mints its own browser
8
+ session; no Google secret is ever needed on a tenant.
9
+
10
+ The token is a bearer value, so it is treated like one: single audience, short
11
+ life, constant-time signature check, no algorithm field to negotiate (there is
12
+ exactly one construction, so `alg=none`-style confusion cannot be expressed).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import base64
18
+ import hashlib
19
+ import hmac
20
+ import json
21
+ import time
22
+
23
+ #: Prefix keeps the format versionable and makes a stray value easy to reject.
24
+ PREFIX = "hjt1"
25
+
26
+ #: A transfer only has to outlive one browser redirect.
27
+ DEFAULT_TTL_SECONDS = 120
28
+
29
+ #: No key, no transfer. Anything shorter than this is not a secret.
30
+ MIN_KEY_BYTES = 32
31
+
32
+
33
+ #: HKDF salt. Changing it invalidates every derived key, so it is versioned.
34
+ DERIVATION_SALT = b"hoja-identity-transfer-v1"
35
+
36
+ #: Derived keys are 32 bytes, the HMAC-SHA256 key size.
37
+ DERIVED_KEY_BYTES = 32
38
+
39
+
40
+ class TransferError(Exception):
41
+ """A transfer token was refused. ``reason`` is safe to log and return."""
42
+
43
+ def __init__(self, reason: str, detail: str = "") -> None:
44
+ super().__init__(detail or reason)
45
+ self.reason = reason
46
+
47
+
48
+ def _b64e(raw: bytes) -> str:
49
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
50
+
51
+
52
+ def _b64d(text: str) -> bytes:
53
+ padding = "=" * (-len(text) % 4)
54
+ return base64.urlsafe_b64decode(text + padding)
55
+
56
+
57
+ def _check_key(key: str | bytes | None) -> bytes:
58
+ if isinstance(key, str):
59
+ key = key.encode("utf-8")
60
+ if not key or len(key) < MIN_KEY_BYTES:
61
+ raise TransferError("key_missing", "A transfer key of at least 32 bytes is required.")
62
+ return key
63
+
64
+
65
+ def tenant_key(master: str | bytes, audience: str) -> str:
66
+ """Derive the one key a given host may hold, from the control-plane master.
67
+
68
+ Domain separation is the point: a tenant stores *this* value, never the
69
+ master, so a compromised tenant cannot compute any other host's key and
70
+ therefore cannot mint an identity for it.
71
+
72
+ The result is text because it travels in an environment variable. Both ends
73
+ must hash the same bytes, so the control plane signs with this *string* and
74
+ the tenant verifies with the string it was given -- never the decoded bytes
75
+ on one side and the text on the other. HKDF-SHA256 with the hostname as
76
+ ``info`` also gives stability (same host, same key) and independence
77
+ (different host, unrelated key).
78
+ """
79
+ from cryptography.hazmat.primitives import hashes
80
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
81
+
82
+ if isinstance(master, str):
83
+ master = master.encode("utf-8")
84
+ if not master or len(master) < MIN_KEY_BYTES:
85
+ raise TransferError("key_missing", "A master key of at least 32 bytes is required.")
86
+ host = (audience or "").strip().lower()
87
+ if not host:
88
+ raise TransferError("claims_missing", "An audience is required to derive a key.")
89
+ return base64.urlsafe_b64encode(
90
+ HKDF(
91
+ algorithm=hashes.SHA256(),
92
+ length=DERIVED_KEY_BYTES,
93
+ salt=DERIVATION_SALT,
94
+ info=host.encode("utf-8"),
95
+ ).derive(master)
96
+ ).decode("ascii").rstrip("=")
97
+
98
+
99
+ def _signature(key: bytes, signing_input: bytes) -> bytes:
100
+ return hmac.new(key, signing_input, hashlib.sha256).digest()
101
+
102
+
103
+ def issue(
104
+ *,
105
+ key: str | bytes | None,
106
+ audience: str,
107
+ email: str,
108
+ subject: str,
109
+ name: str | None = None,
110
+ picture: str | None = None,
111
+ email_verified: bool = False,
112
+ ttl_seconds: int = DEFAULT_TTL_SECONDS,
113
+ now: float | None = None,
114
+ ) -> str:
115
+ """Mint a transfer token for exactly one audience (a tenant hostname)."""
116
+ signing_key = _check_key(key)
117
+ if not audience or not email or not subject:
118
+ raise TransferError("claims_missing", "audience, email and subject are required.")
119
+ if not email_verified:
120
+ # A tenant must never have to re-derive this: only verified addresses
121
+ # are ever handed across, so an unverified one is a programming error.
122
+ raise TransferError("email_unverified", "Only a verified address may be transferred.")
123
+ moment = time.time() if now is None else now
124
+ payload = {
125
+ "aud": audience.strip().lower(),
126
+ "email": email.strip().lower(),
127
+ "sub": subject,
128
+ "name": name,
129
+ "picture": picture,
130
+ "ev": True,
131
+ "iat": int(moment),
132
+ "exp": int(moment) + max(1, int(ttl_seconds)),
133
+ }
134
+ body = _b64e(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8"))
135
+ signing_input = f"{PREFIX}.{body}".encode("ascii")
136
+ return f"{PREFIX}.{body}.{_b64e(_signature(signing_key, signing_input))}"
137
+
138
+
139
+ def redeem(
140
+ *,
141
+ key: str | bytes | None,
142
+ token: str | None,
143
+ audience: str,
144
+ now: float | None = None,
145
+ ) -> dict:
146
+ """Verify a transfer token for this origin and return its claims.
147
+
148
+ Every failure raises :class:`TransferError`; the caller must not learn more
149
+ than ``reason`` (a bad signature and a wrong audience both mean "no").
150
+ """
151
+ signing_key = _check_key(key)
152
+ if not token or token.count(".") != 2:
153
+ raise TransferError("malformed", "Token is not in the expected format.")
154
+ prefix, body, signature = token.split(".")
155
+ if prefix != PREFIX:
156
+ raise TransferError("malformed", "Unknown token prefix.")
157
+ signing_input = f"{prefix}.{body}".encode("ascii")
158
+ try:
159
+ given = _b64d(signature)
160
+ except Exception as exc: # noqa: BLE001 - any decode failure is a refusal
161
+ raise TransferError("malformed", "Signature is not valid base64url.") from exc
162
+ if not hmac.compare_digest(given, _signature(signing_key, signing_input)):
163
+ raise TransferError("bad_signature", "Signature does not match.")
164
+ try:
165
+ claims = json.loads(_b64d(body))
166
+ except Exception as exc: # noqa: BLE001
167
+ raise TransferError("malformed", "Payload is not valid JSON.") from exc
168
+ if not isinstance(claims, dict):
169
+ raise TransferError("malformed", "Payload is not an object.")
170
+ moment = time.time() if now is None else now
171
+ if int(claims.get("exp", 0)) < int(moment):
172
+ raise TransferError("expired", "Token has expired.")
173
+ if str(claims.get("aud", "")).lower() != audience.strip().lower():
174
+ # A token minted for one tenant is useless on another.
175
+ raise TransferError("wrong_audience", "Token was issued for another host.")
176
+ if claims.get("ev") is not True:
177
+ raise TransferError("email_unverified", "Address was never verified.")
178
+ if not claims.get("email") or not claims.get("sub"):
179
+ raise TransferError("claims_missing", "Token is missing email or subject.")
180
+ return claims
181
+
182
+
183
+ def tenant_target(
184
+ value: str | None,
185
+ *,
186
+ apex: str = "hoja.work",
187
+ reserved: tuple[str, ...] = ("app", "www"),
188
+ ) -> str | None:
189
+ """Normalise a return target on a *tenant* origin of ours, or return None.
190
+
191
+ The handoff token is signed for one host, so this decides which hosts a
192
+ person may be sent back to. Only absolute https URLs under our own apex
193
+ qualify, and the reserved control-plane names never do; anything else is
194
+ refused, which is what keeps this from being an open redirect.
195
+ """
196
+ from urllib.parse import urlsplit
197
+
198
+ candidate = (value or "").strip()
199
+ parts = urlsplit(candidate)
200
+ host = (parts.hostname or "").lower()
201
+ if parts.scheme != "https":
202
+ return None
203
+ if not host.endswith("." + apex) or host == apex:
204
+ return None
205
+ if host.split(".", 1)[0] in reserved:
206
+ return None
207
+ path = parts.path or "/"
208
+ if not path.startswith("/"):
209
+ return None
210
+ return f"https://{host}{path}"