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.
- VERSION +1 -0
- google_workspace/__init__.py +19 -0
- google_workspace/client.py +253 -0
- google_workspace/config.py +39 -0
- google_workspace/errors.py +19 -0
- google_workspace/mcp_server.py +100 -0
- google_workspace/oauth.py +131 -0
- google_workspace/principal.py +83 -0
- google_workspace/py.typed +0 -0
- google_workspace/tools.py +64 -0
- google_workspace/writes.py +44 -0
- hoja/__init__.py +29 -0
- hoja/__main__.py +6 -0
- hoja/auth.py +42 -0
- hoja/cli.py +161 -0
- hoja/cli_state.py +55 -0
- hoja/client.py +268 -0
- hoja/commands/__init__.py +4 -0
- hoja/commands/auth_cmd.py +271 -0
- hoja/commands/comment.py +149 -0
- hoja/commands/cycle.py +75 -0
- hoja/commands/init.py +108 -0
- hoja/commands/issue.py +398 -0
- hoja/commands/label.py +163 -0
- hoja/commands/memory.py +240 -0
- hoja/commands/project.py +56 -0
- hoja/commands/raw.py +50 -0
- hoja/commands/team.py +102 -0
- hoja/commands/update.py +162 -0
- hoja/config.py +362 -0
- hoja/errors.py +107 -0
- hoja/filters.py +150 -0
- hoja/graphql/__init__.py +5 -0
- hoja/graphql/fragments.py +138 -0
- hoja/graphql/mutations.py +160 -0
- hoja/graphql/queries.py +245 -0
- hoja/mcp/__init__.py +27 -0
- hoja/mcp/content.py +151 -0
- hoja/mcp/prompts.py +298 -0
- hoja/mcp/resources.py +213 -0
- hoja/mcp/server.py +189 -0
- hoja/memory_board.py +370 -0
- hoja/models/__init__.py +37 -0
- hoja/models/base.py +64 -0
- hoja/models/cycle.py +32 -0
- hoja/models/enums.py +62 -0
- hoja/models/issue.py +99 -0
- hoja/models/label.py +17 -0
- hoja/models/project.py +60 -0
- hoja/models/team.py +31 -0
- hoja/models/user.py +32 -0
- hoja/models/workflow.py +65 -0
- hoja/output.py +410 -0
- hoja/skill_content/commands.md +222 -0
- hoja/skill_content/examples.md +193 -0
- hoja/skill_content/filters.md +101 -0
- hoja/skill_content/output-formats.md +92 -0
- hoja/skill_content/overview.md +123 -0
- hoja/skill_content/workflows.md +174 -0
- hoja_cli-0.21.4.dist-info/METADATA +279 -0
- hoja_cli-0.21.4.dist-info/RECORD +107 -0
- hoja_cli-0.21.4.dist-info/WHEEL +4 -0
- hoja_cli-0.21.4.dist-info/entry_points.txt +4 -0
- hoja_cli-0.21.4.dist-info/licenses/LICENSE +21 -0
- hoja_server/README.md +135 -0
- hoja_server/__init__.py +11 -0
- hoja_server/abac.py +116 -0
- hoja_server/agent_chat.py +280 -0
- hoja_server/agent_conversations.py +91 -0
- hoja_server/agent_durable.py +332 -0
- hoja_server/agent_prompt.py +117 -0
- hoja_server/agent_threads.py +96 -0
- hoja_server/agent_uploads.py +60 -0
- hoja_server/app.py +2189 -0
- hoja_server/cadence.py +231 -0
- hoja_server/cli.py +191 -0
- hoja_server/cloudflare_realtime.py +110 -0
- hoja_server/comment_policy.py +70 -0
- hoja_server/connector_actions.py +119 -0
- hoja_server/connectors_api.py +375 -0
- hoja_server/db.py +1816 -0
- hoja_server/denials.py +18 -0
- hoja_server/deployment.py +28 -0
- hoja_server/email_adapter.py +94 -0
- hoja_server/google_login.py +217 -0
- hoja_server/google_oidc.py +342 -0
- hoja_server/identity_transfer.py +210 -0
- hoja_server/mcp_oauth.py +623 -0
- hoja_server/mcp_tools.py +579 -0
- hoja_server/meeting_policy.py +179 -0
- hoja_server/meetings.py +1332 -0
- hoja_server/meetings_api.py +909 -0
- hoja_server/model_providers.py +205 -0
- hoja_server/realtime.py +690 -0
- hoja_server/resolvers.py +1281 -0
- hoja_server/schema.graphql +477 -0
- hoja_server/schema_sdl.py +8 -0
- hoja_server/secrets_box.py +39 -0
- hoja_server/signup_config.py +292 -0
- hoja_server/signup_gate.py +393 -0
- hoja_server/signup_policy.py +97 -0
- hoja_server/signup_store.py +577 -0
- hoja_server/store.py +2179 -0
- hoja_server/sync.py +249 -0
- hoja_server/tenant_context.py +131 -0
- hoja_server/turnstile.py +81 -0
- hoja_server/writer.py +1262 -0
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""Configuration for the hosted sign-up surface, read once, fail-closed.
|
|
2
|
+
|
|
3
|
+
The gate must never be permissive because a variable was forgotten. Three
|
|
4
|
+
rules follow, and they are the whole point of this module:
|
|
5
|
+
|
|
6
|
+
1. ``HOJA_SIGNUP_MODE`` defaults to ``closed``. An unconfigured deployment
|
|
7
|
+
refuses every sign-up with ``signup_closed`` instead of allowing one.
|
|
8
|
+
2. A mode other than ``closed`` **requires** all five Google/Turnstile
|
|
9
|
+
variables. Missing any of them raises :class:`SignupConfigError` at app
|
|
10
|
+
startup — a clear error, not a silent allow.
|
|
11
|
+
3. A *partially* configured deployment (some set, some empty) raises too,
|
|
12
|
+
whatever the mode: half a flow is a mistake, not a configuration.
|
|
13
|
+
|
|
14
|
+
Nothing in this module talks to the network or to the database.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from urllib.parse import urlsplit
|
|
23
|
+
|
|
24
|
+
SIGNUP_MODES = ("closed", "invite", "open")
|
|
25
|
+
|
|
26
|
+
#: The exact environment variable names the gate reads. These are the contract.
|
|
27
|
+
REQUIRED_ENV = (
|
|
28
|
+
"GOOGLE_CLIENT_ID",
|
|
29
|
+
"GOOGLE_CLIENT_SECRET",
|
|
30
|
+
"GOOGLE_REDIRECT_URI",
|
|
31
|
+
"TURNSTILE_SECRET_KEY",
|
|
32
|
+
"TURNSTILE_EXPECTED_HOSTNAME",
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
MODE_ENV = "HOJA_SIGNUP_MODE"
|
|
36
|
+
|
|
37
|
+
#: The Turnstile *site* key. Public by design — it ships to the browser, so it is
|
|
38
|
+
#: deliberately **not** in ``REQUIRED_ENV`` and never gates what the server
|
|
39
|
+
#: accepts. Missing only means the page cannot render a widget, and the page then
|
|
40
|
+
#: says "sign-up unavailable" instead of rendering one that cannot work.
|
|
41
|
+
SITE_KEY_ENV = "TURNSTILE_SITE_KEY"
|
|
42
|
+
|
|
43
|
+
#: Cloudflare's widget script, explicit rendering (the page calls render() itself,
|
|
44
|
+
#: so the implicit-render auto-scan is never what creates the widget).
|
|
45
|
+
TURNSTILE_SCRIPT_URL = (
|
|
46
|
+
"https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
REDIRECT_ALLOWLIST_ENV = "GOOGLE_REDIRECT_URI_ALLOWLIST"
|
|
50
|
+
HD_ENV = "HOJA_GOOGLE_HD"
|
|
51
|
+
IDENTITY_CAP_ENV = "HOJA_SIGNUP_IDENTITY_CAP"
|
|
52
|
+
IP_CAP_ENV = "HOJA_SIGNUP_IP_CAP"
|
|
53
|
+
IP_WINDOW_ENV = "HOJA_SIGNUP_IP_WINDOW_SECONDS"
|
|
54
|
+
TENANT_REGISTRY_ENV = "HOJA_TENANT_REGISTRY"
|
|
55
|
+
|
|
56
|
+
#: The suffix under which a provisioned workspace lives. The control plane uses
|
|
57
|
+
#: it only to tell an authenticated requester where their ready workspace is.
|
|
58
|
+
TENANT_BASE_DOMAIN_ENV = "HOJA_TENANT_BASE_DOMAIN"
|
|
59
|
+
DEFAULT_TENANT_BASE_DOMAIN = "hoja.work"
|
|
60
|
+
|
|
61
|
+
#: Where a tenant origin sends its sign-in. Google cannot register a wildcard
|
|
62
|
+
#: redirect, so every tenant delegates the code exchange to this one origin.
|
|
63
|
+
CONTROL_PLANE_ENV = "HOJA_CONTROL_PLANE_URL"
|
|
64
|
+
|
|
65
|
+
#: Shared HMAC key for the control plane -> tenant identity handoff. Optional on
|
|
66
|
+
#: a single-origin install; when present it must be long enough to be a secret.
|
|
67
|
+
TRANSFER_KEY_ENV = "HOJA_IDENTITY_TRANSFER_KEY"
|
|
68
|
+
|
|
69
|
+
#: The control plane's master, from which every tenant's key is derived. It is
|
|
70
|
+
#: deliberately a different variable from TRANSFER_KEY_ENV: a tenant must never
|
|
71
|
+
#: be able to hold the master and mint identities for its neighbours.
|
|
72
|
+
TRANSFER_MASTER_ENV = "HOJA_IDENTITY_TRANSFER_MASTER"
|
|
73
|
+
|
|
74
|
+
#: A site key is an opaque token, not a URL and not a compound value.
|
|
75
|
+
_SITE_KEY_RE = re.compile(r"^[A-Za-z0-9_-]{8,128}$")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class SignupConfigError(RuntimeError):
|
|
79
|
+
"""The sign-up surface cannot be enabled safely with this environment."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _int_env(environ, name: str, default: int, *, minimum: int = 1) -> int:
|
|
83
|
+
raw = (environ.get(name) or "").strip()
|
|
84
|
+
if not raw:
|
|
85
|
+
return default
|
|
86
|
+
try:
|
|
87
|
+
value = int(raw)
|
|
88
|
+
except ValueError as exc:
|
|
89
|
+
raise SignupConfigError(f"{name} must be an integer, got {raw!r}.") from exc
|
|
90
|
+
if value < minimum:
|
|
91
|
+
raise SignupConfigError(f"{name} must be at least {minimum}, got {value}.")
|
|
92
|
+
return value
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _validate_redirect_uri(uri: str) -> str:
|
|
96
|
+
"""An absolute URI with no query or fragment, https (or loopback http)."""
|
|
97
|
+
parts = urlsplit(uri)
|
|
98
|
+
if not parts.scheme or not parts.netloc:
|
|
99
|
+
raise SignupConfigError(f"GOOGLE_REDIRECT_URI must be an absolute URI, got {uri!r}.")
|
|
100
|
+
if parts.query or parts.fragment:
|
|
101
|
+
raise SignupConfigError(
|
|
102
|
+
f"GOOGLE_REDIRECT_URI must not carry a query or fragment, got {uri!r}.")
|
|
103
|
+
loopback = (parts.hostname or "") in ("localhost", "127.0.0.1", "::1")
|
|
104
|
+
if parts.scheme != "https" and not (parts.scheme == "http" and loopback):
|
|
105
|
+
raise SignupConfigError(
|
|
106
|
+
f"GOOGLE_REDIRECT_URI must be https (http only for loopback), got {uri!r}.")
|
|
107
|
+
return uri
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _validate_hostname(value: str) -> str:
|
|
111
|
+
if any(ch in value for ch in "/?#@") or "://" in value:
|
|
112
|
+
raise SignupConfigError(
|
|
113
|
+
f"TURNSTILE_EXPECTED_HOSTNAME must be a bare hostname, got {value!r}.")
|
|
114
|
+
return value.strip().lower()
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _validate_site_key(value: str) -> str:
|
|
118
|
+
"""The public widget key: a bare token, or ``""`` when it is not set."""
|
|
119
|
+
if not value:
|
|
120
|
+
return ""
|
|
121
|
+
if not _SITE_KEY_RE.match(value):
|
|
122
|
+
raise SignupConfigError(
|
|
123
|
+
f"{SITE_KEY_ENV} must be a bare Turnstile site key "
|
|
124
|
+
f"(letters, digits, '-' and '_' only), got {value!r}.")
|
|
125
|
+
return value
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass(frozen=True)
|
|
129
|
+
class SignupConfig:
|
|
130
|
+
"""The validated sign-up configuration. ``configured`` gates the endpoints."""
|
|
131
|
+
|
|
132
|
+
mode: str = "closed"
|
|
133
|
+
google_client_id: str = ""
|
|
134
|
+
google_client_secret: str = ""
|
|
135
|
+
redirect_uris: tuple[str, ...] = ()
|
|
136
|
+
turnstile_secret_key: str = ""
|
|
137
|
+
turnstile_site_key: str = ""
|
|
138
|
+
turnstile_expected_hostname: str = ""
|
|
139
|
+
google_hd: str | None = None
|
|
140
|
+
identity_cap: int = 1
|
|
141
|
+
ip_cap: int = 2
|
|
142
|
+
ip_window_seconds: int = 24 * 60 * 60
|
|
143
|
+
tenant_registry: str | None = None
|
|
144
|
+
tenant_base_domain: str = DEFAULT_TENANT_BASE_DOMAIN
|
|
145
|
+
#: Where tenant origins delegate Google sign-in, and the key they share with
|
|
146
|
+
#: it. Both empty on a single-origin install; both set on a hosted one.
|
|
147
|
+
control_plane_url: str | None = None
|
|
148
|
+
identity_transfer_key: str | None = None
|
|
149
|
+
identity_transfer_master: str | None = None
|
|
150
|
+
flow_ttl_seconds: int = 600
|
|
151
|
+
session_days: int = 30
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def configured(self) -> bool:
|
|
155
|
+
"""True when every credential the OIDC + Turnstile path needs is present."""
|
|
156
|
+
return bool(
|
|
157
|
+
self.google_client_id
|
|
158
|
+
and self.google_client_secret
|
|
159
|
+
and self.redirect_uris
|
|
160
|
+
and self.turnstile_secret_key
|
|
161
|
+
and self.turnstile_expected_hostname
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
@property
|
|
165
|
+
def public_widget_available(self) -> bool:
|
|
166
|
+
"""True when a browser can render a widget *and* the gate can verify it.
|
|
167
|
+
|
|
168
|
+
Both halves are required: a site key with no server secret renders a
|
|
169
|
+
widget whose token the gate can never spend, which is worse than saying
|
|
170
|
+
"unavailable" — so this is False for a half-configured deployment even
|
|
171
|
+
though ``configured`` and the presence of a key are each true on their
|
|
172
|
+
own.
|
|
173
|
+
"""
|
|
174
|
+
return bool(self.configured and self.turnstile_site_key)
|
|
175
|
+
|
|
176
|
+
def redirect_uri_for(self, host: str) -> str | None:
|
|
177
|
+
"""The exact allow-listed redirect URI for ``host``, or None.
|
|
178
|
+
|
|
179
|
+
One hostname, one URI: the URI is compared as a whole string later, so a
|
|
180
|
+
host that is not on the list simply has no redirect URI and the flow
|
|
181
|
+
cannot start.
|
|
182
|
+
"""
|
|
183
|
+
wanted = (host or "").strip().lower().split(":")[0]
|
|
184
|
+
for uri in self.redirect_uris:
|
|
185
|
+
if (urlsplit(uri).hostname or "").lower() == wanted:
|
|
186
|
+
return uri
|
|
187
|
+
return None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def load_signup_config(environ: dict[str, str] | None = None) -> SignupConfig:
|
|
191
|
+
"""Parse and validate the environment. Raises :class:`SignupConfigError`."""
|
|
192
|
+
env = os.environ if environ is None else environ
|
|
193
|
+
|
|
194
|
+
mode = (env.get(MODE_ENV) or "closed").strip().lower()
|
|
195
|
+
if mode not in SIGNUP_MODES:
|
|
196
|
+
raise SignupConfigError(
|
|
197
|
+
f"{MODE_ENV} must be one of {', '.join(SIGNUP_MODES)}; got {mode!r}.")
|
|
198
|
+
|
|
199
|
+
values = {name: (env.get(name) or "").strip() for name in REQUIRED_ENV}
|
|
200
|
+
missing = [name for name, value in values.items() if not value]
|
|
201
|
+
|
|
202
|
+
if mode != "closed" and missing:
|
|
203
|
+
raise SignupConfigError(
|
|
204
|
+
f"{MODE_ENV}={mode} requires {', '.join(missing)}. "
|
|
205
|
+
"Sign-up stays closed until every one is set "
|
|
206
|
+
f"(set {MODE_ENV}=closed to run without them).")
|
|
207
|
+
if missing and len(missing) != len(REQUIRED_ENV):
|
|
208
|
+
raise SignupConfigError(
|
|
209
|
+
"The sign-up configuration is incomplete: missing "
|
|
210
|
+
f"{', '.join(missing)} (present: "
|
|
211
|
+
f"{', '.join(n for n in REQUIRED_ENV if n not in missing)}). "
|
|
212
|
+
"Refusing to start rather than half-enable the gate.")
|
|
213
|
+
|
|
214
|
+
allowlist = (env.get(REDIRECT_ALLOWLIST_ENV) or "").strip()
|
|
215
|
+
raw_uris = [item.strip() for item in allowlist.split(",") if item.strip()]
|
|
216
|
+
if not raw_uris and values["GOOGLE_REDIRECT_URI"]:
|
|
217
|
+
raw_uris = [values["GOOGLE_REDIRECT_URI"]]
|
|
218
|
+
redirect_uris = tuple(dict.fromkeys(_validate_redirect_uri(uri) for uri in raw_uris))
|
|
219
|
+
|
|
220
|
+
hostname = _validate_hostname(values["TURNSTILE_EXPECTED_HOSTNAME"]) if values[
|
|
221
|
+
"TURNSTILE_EXPECTED_HOSTNAME"] else ""
|
|
222
|
+
|
|
223
|
+
site_key = _validate_site_key((env.get(SITE_KEY_ENV) or "").strip())
|
|
224
|
+
if site_key and site_key == values["TURNSTILE_SECRET_KEY"]:
|
|
225
|
+
# The site key ships to every browser. Copying the secret into it would
|
|
226
|
+
# publish the secret, and Cloudflare's two keys look alike enough that
|
|
227
|
+
# this mistake is one edit away — so refuse to start instead.
|
|
228
|
+
raise SignupConfigError(
|
|
229
|
+
f"{SITE_KEY_ENV} is identical to TURNSTILE_SECRET_KEY. The site key is "
|
|
230
|
+
"public and goes into the page bundle; the secret key must never be "
|
|
231
|
+
"used as the widget key.")
|
|
232
|
+
|
|
233
|
+
return SignupConfig(
|
|
234
|
+
mode=mode,
|
|
235
|
+
google_client_id=values["GOOGLE_CLIENT_ID"],
|
|
236
|
+
google_client_secret=values["GOOGLE_CLIENT_SECRET"],
|
|
237
|
+
redirect_uris=redirect_uris,
|
|
238
|
+
turnstile_secret_key=values["TURNSTILE_SECRET_KEY"],
|
|
239
|
+
turnstile_site_key=site_key,
|
|
240
|
+
turnstile_expected_hostname=hostname,
|
|
241
|
+
google_hd=(env.get(HD_ENV) or "").strip().lower() or None,
|
|
242
|
+
identity_cap=_int_env(env, IDENTITY_CAP_ENV, 1),
|
|
243
|
+
ip_cap=_int_env(env, IP_CAP_ENV, 2),
|
|
244
|
+
ip_window_seconds=_int_env(env, IP_WINDOW_ENV, 24 * 60 * 60, minimum=60),
|
|
245
|
+
tenant_registry=(env.get(TENANT_REGISTRY_ENV) or "").strip() or None,
|
|
246
|
+
tenant_base_domain=(
|
|
247
|
+
_validate_hostname((env.get(TENANT_BASE_DOMAIN_ENV) or "").strip())
|
|
248
|
+
if (env.get(TENANT_BASE_DOMAIN_ENV) or "").strip()
|
|
249
|
+
else DEFAULT_TENANT_BASE_DOMAIN
|
|
250
|
+
),
|
|
251
|
+
control_plane_url=control_plane_url(env),
|
|
252
|
+
identity_transfer_key=identity_transfer_key(env),
|
|
253
|
+
identity_transfer_master=identity_transfer_master(env),
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def control_plane_url(environ=None) -> str | None:
|
|
258
|
+
"""The origin a tenant delegates Google sign-in to, or None."""
|
|
259
|
+
env = os.environ if environ is None else environ
|
|
260
|
+
raw = (env.get(CONTROL_PLANE_ENV) or "").strip().rstrip("/")
|
|
261
|
+
if not raw:
|
|
262
|
+
return None
|
|
263
|
+
parts = urlsplit(raw)
|
|
264
|
+
if parts.scheme != "https" or not parts.netloc:
|
|
265
|
+
raise SignupConfigError(f"{CONTROL_PLANE_ENV} must be an https origin, got {raw!r}.")
|
|
266
|
+
return raw
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def identity_transfer_master(environ=None) -> str | None:
|
|
270
|
+
"""The control plane's key-derivation master, or None."""
|
|
271
|
+
env = os.environ if environ is None else environ
|
|
272
|
+
raw = (env.get(TRANSFER_MASTER_ENV) or "").strip()
|
|
273
|
+
if not raw:
|
|
274
|
+
return None
|
|
275
|
+
if len(raw) < 32:
|
|
276
|
+
raise SignupConfigError(
|
|
277
|
+
f"{TRANSFER_MASTER_ENV} must be at least 32 characters; every tenant key is derived from it."
|
|
278
|
+
)
|
|
279
|
+
return raw
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def identity_transfer_key(environ=None) -> str | None:
|
|
283
|
+
"""The shared handoff key, or None when handoff is not configured."""
|
|
284
|
+
env = os.environ if environ is None else environ
|
|
285
|
+
raw = (env.get(TRANSFER_KEY_ENV) or "").strip()
|
|
286
|
+
if not raw:
|
|
287
|
+
return None
|
|
288
|
+
if len(raw) < 32:
|
|
289
|
+
raise SignupConfigError(
|
|
290
|
+
f"{TRANSFER_KEY_ENV} must be at least 32 characters; it signs signed-in identities."
|
|
291
|
+
)
|
|
292
|
+
return raw
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
"""The sign-up gate: ``anonymous -> google_verified -> human_verified -> eligible``.
|
|
2
|
+
|
|
3
|
+
This module is the only place that may decide ``eligible``, and it decides on
|
|
4
|
+
three independent facts:
|
|
5
|
+
|
|
6
|
+
| Layer | Fact | Evidence |
|
|
7
|
+
| --- | --- | --- |
|
|
8
|
+
| Google OIDC | a verified person | a live ``signup_session`` tied to an identity recorded only after a fully validated ``id_token`` (``email_verified == true``) |
|
|
9
|
+
| Turnstile | a human at the keyboard | a token verified server-side *now*, with our secret, our hostname and this client's address, spent exactly once |
|
|
10
|
+
| Capacity/policy | a workspace we are willing to create | the mode allows it, the invite exists, the caps are not exceeded, and the slug is free and not reserved |
|
|
11
|
+
|
|
12
|
+
What it never does: create a database, a container, a route or a DNS record, or
|
|
13
|
+
call a provisioner. Success is one ``signup_eligibility`` row — a request the
|
|
14
|
+
provisioner may pick up on its own schedule.
|
|
15
|
+
|
|
16
|
+
Refusal order is cheapest-first and stable, so a caller can branch on ``reason``:
|
|
17
|
+
|
|
18
|
+
1. ``signup_unconfigured`` — the deployment has no credentials
|
|
19
|
+
2. ``not_authenticated`` — no live Google-verified session
|
|
20
|
+
3. ``signup_closed`` / ``domain_not_allowed`` — policy that costs no I/O
|
|
21
|
+
4. ``slug_required`` / ``invalid_slug`` / ``reserved_slug`` — pure syntax
|
|
22
|
+
5. ``turnstile_missing`` / ``turnstile_failed`` / ``turnstile_replayed`` — the human layer
|
|
23
|
+
6. the idempotent repeat (`eligible` again, no write)
|
|
24
|
+
7. ``invite_required``
|
|
25
|
+
8. ``identity_cap_exceeded`` / ``ip_cap_exceeded``
|
|
26
|
+
9. ``slug_taken``
|
|
27
|
+
10. ``eligible``
|
|
28
|
+
|
|
29
|
+
Step 4 comes before step 5 on purpose: an invalid label is refused before a
|
|
30
|
+
Turnstile token is spent, because refusing it costs nothing.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
from dataclasses import dataclass
|
|
36
|
+
from datetime import datetime, timedelta, timezone
|
|
37
|
+
from enum import Enum
|
|
38
|
+
from collections.abc import Callable
|
|
39
|
+
|
|
40
|
+
from hoja_server import turnstile as turnstile_module
|
|
41
|
+
from hoja_server.signup_config import SignupConfig
|
|
42
|
+
from hoja_server.signup_policy import SlugRefused, validate_slug
|
|
43
|
+
from hoja_server.signup_store import EligibilityConflict, SignupStore
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class SignupState(str, Enum):
|
|
47
|
+
"""Where the request stands in the state machine. Never skips a step."""
|
|
48
|
+
|
|
49
|
+
ANONYMOUS = "anonymous"
|
|
50
|
+
GOOGLE_VERIFIED = "google_verified"
|
|
51
|
+
HUMAN_VERIFIED = "human_verified"
|
|
52
|
+
ELIGIBLE = "eligible"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class SignupReason(str, Enum):
|
|
56
|
+
"""Stable machine-readable refusal codes. Callers may branch on these."""
|
|
57
|
+
|
|
58
|
+
SIGNUP_UNCONFIGURED = "signup_unconfigured"
|
|
59
|
+
NOT_AUTHENTICATED = "not_authenticated"
|
|
60
|
+
SIGNUP_CLOSED = "signup_closed"
|
|
61
|
+
DOMAIN_NOT_ALLOWED = "domain_not_allowed"
|
|
62
|
+
SLUG_REQUIRED = "slug_required"
|
|
63
|
+
INVALID_SLUG = "invalid_slug"
|
|
64
|
+
RESERVED_SLUG = "reserved_slug"
|
|
65
|
+
TURNSTILE_MISSING = "turnstile_missing"
|
|
66
|
+
TURNSTILE_FAILED = "turnstile_failed"
|
|
67
|
+
TURNSTILE_REPLAYED = "turnstile_replayed"
|
|
68
|
+
INVITE_REQUIRED = "invite_required"
|
|
69
|
+
IDENTITY_CAP_EXCEEDED = "identity_cap_exceeded"
|
|
70
|
+
IP_CAP_EXCEEDED = "ip_cap_exceeded"
|
|
71
|
+
SLUG_TAKEN = "slug_taken"
|
|
72
|
+
ELIGIBLE = "eligible"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
#: Two refusals ``POST /api/signup`` adds before the gate runs: the same-origin
|
|
76
|
+
#: check and the body parser. They are named here, next to the enum, so the route
|
|
77
|
+
#: and the page share one vocabulary instead of agreeing by copy-paste.
|
|
78
|
+
CROSS_SITE_REQUEST = "cross_site_request"
|
|
79
|
+
INVALID_REQUEST = "invalid_request"
|
|
80
|
+
|
|
81
|
+
#: Every ``reason`` the sign-up endpoint can answer with — the one list the page's
|
|
82
|
+
#: copy map is checked against. ``eligible`` is included because it is a member of
|
|
83
|
+
#: :class:`SignupReason` (it is delivered as ``state``, with ``reason: null``), so
|
|
84
|
+
#: the tuple stays a faithful enumeration rather than a hand-curated subset.
|
|
85
|
+
#:
|
|
86
|
+
#: ``frontend/src/signup/reasonCopy.ts`` must map each entry;
|
|
87
|
+
#: ``tests/test_signup_page.py`` asserts the two lists are equal, so a new code
|
|
88
|
+
#: cannot be added here without the page being updated (and vice versa).
|
|
89
|
+
SIGNUP_REASON_CODES = tuple(
|
|
90
|
+
reason.value for reason in SignupReason
|
|
91
|
+
) + (CROSS_SITE_REQUEST, INVALID_REQUEST)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
_SLUG_REASON_STATUS = {
|
|
95
|
+
"slug_required": (SignupReason.SLUG_REQUIRED, 422),
|
|
96
|
+
"invalid_slug": (SignupReason.INVALID_SLUG, 422),
|
|
97
|
+
"reserved_slug": (SignupReason.RESERVED_SLUG, 403),
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True)
|
|
102
|
+
class SignupDecision:
|
|
103
|
+
"""One evaluated request. ``reason`` is ``None`` only when eligible."""
|
|
104
|
+
|
|
105
|
+
state: SignupState
|
|
106
|
+
reason: SignupReason | None
|
|
107
|
+
message: str
|
|
108
|
+
status_code: int
|
|
109
|
+
google_verified: bool = False
|
|
110
|
+
human_verified: bool = False
|
|
111
|
+
eligibility: dict | None = None
|
|
112
|
+
created: bool = False
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def ok(self) -> bool:
|
|
116
|
+
return self.reason is None
|
|
117
|
+
|
|
118
|
+
def as_dict(self) -> dict:
|
|
119
|
+
body = {
|
|
120
|
+
"ok": self.ok,
|
|
121
|
+
"state": self.state.value,
|
|
122
|
+
"reason": self.reason.value if self.reason else None,
|
|
123
|
+
"message": self.message,
|
|
124
|
+
"googleVerified": self.google_verified,
|
|
125
|
+
"humanVerified": self.human_verified,
|
|
126
|
+
}
|
|
127
|
+
if self.eligibility:
|
|
128
|
+
body.update(
|
|
129
|
+
{
|
|
130
|
+
"eligibilityId": self.eligibility.get("id"),
|
|
131
|
+
"slug": self.eligibility.get("slug"),
|
|
132
|
+
"status": self.eligibility.get("status"),
|
|
133
|
+
"alreadyEligible": not self.created,
|
|
134
|
+
}
|
|
135
|
+
)
|
|
136
|
+
return body
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _refuse(
|
|
140
|
+
state: SignupState,
|
|
141
|
+
reason: SignupReason,
|
|
142
|
+
message: str,
|
|
143
|
+
status_code: int,
|
|
144
|
+
*,
|
|
145
|
+
google_verified: bool = False,
|
|
146
|
+
human_verified: bool = False,
|
|
147
|
+
) -> SignupDecision:
|
|
148
|
+
return SignupDecision(
|
|
149
|
+
state=state,
|
|
150
|
+
reason=reason,
|
|
151
|
+
message=message,
|
|
152
|
+
status_code=status_code,
|
|
153
|
+
google_verified=google_verified,
|
|
154
|
+
human_verified=human_verified,
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class SignupGate:
|
|
159
|
+
"""Evaluates one ``POST /api/signup`` against the three layers."""
|
|
160
|
+
|
|
161
|
+
def __init__(
|
|
162
|
+
self,
|
|
163
|
+
*,
|
|
164
|
+
config: SignupConfig,
|
|
165
|
+
store: SignupStore,
|
|
166
|
+
verifier: Callable[..., turnstile_module.TurnstileResult] | None = None,
|
|
167
|
+
clock: Callable[[], datetime] | None = None,
|
|
168
|
+
):
|
|
169
|
+
self.config = config
|
|
170
|
+
self.store = store
|
|
171
|
+
self.verifier = verifier or turnstile_module.verify_turnstile
|
|
172
|
+
self.clock = clock or (lambda: datetime.now(timezone.utc))
|
|
173
|
+
|
|
174
|
+
def evaluate(
|
|
175
|
+
self,
|
|
176
|
+
*,
|
|
177
|
+
identity: dict | None,
|
|
178
|
+
slug: object,
|
|
179
|
+
turnstile_token: str | None,
|
|
180
|
+
client_ip: str | None,
|
|
181
|
+
) -> SignupDecision:
|
|
182
|
+
"""Evaluate one request. Pure with respect to the outside world except
|
|
183
|
+
for the injected Turnstile verifier and the gate's own tables."""
|
|
184
|
+
config, store, now = self.config, self.store, self.clock()
|
|
185
|
+
|
|
186
|
+
# 1. Is the surface even configured? Fail closed, never silently allow.
|
|
187
|
+
if not config.configured:
|
|
188
|
+
return _refuse(
|
|
189
|
+
SignupState.ANONYMOUS,
|
|
190
|
+
SignupReason.SIGNUP_UNCONFIGURED,
|
|
191
|
+
"Sign-up is not configured on this deployment.",
|
|
192
|
+
503,
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
# 2. google_verified: a live session whose identity came from a fully
|
|
196
|
+
# validated id_token. No session, no gate.
|
|
197
|
+
if (
|
|
198
|
+
not identity
|
|
199
|
+
or not identity.get("google_verified_at")
|
|
200
|
+
or not identity.get("email_verified")
|
|
201
|
+
):
|
|
202
|
+
return _refuse(
|
|
203
|
+
SignupState.ANONYMOUS,
|
|
204
|
+
SignupReason.NOT_AUTHENTICATED,
|
|
205
|
+
"Sign in with Google before requesting a workspace.",
|
|
206
|
+
401,
|
|
207
|
+
)
|
|
208
|
+
google_verified = True
|
|
209
|
+
|
|
210
|
+
# 3. Policy that costs no I/O.
|
|
211
|
+
if config.mode == "closed":
|
|
212
|
+
return _refuse(
|
|
213
|
+
SignupState.GOOGLE_VERIFIED,
|
|
214
|
+
SignupReason.SIGNUP_CLOSED,
|
|
215
|
+
"New workspaces are not open yet.",
|
|
216
|
+
403,
|
|
217
|
+
google_verified=google_verified,
|
|
218
|
+
)
|
|
219
|
+
if config.google_hd and (identity.get("hosted_domain") or "") != config.google_hd:
|
|
220
|
+
return _refuse(
|
|
221
|
+
SignupState.GOOGLE_VERIFIED,
|
|
222
|
+
SignupReason.DOMAIN_NOT_ALLOWED,
|
|
223
|
+
"This sign-up page only accepts the configured Google Workspace domain.",
|
|
224
|
+
403,
|
|
225
|
+
google_verified=google_verified,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
# 4. Slug syntax and reserved names (cheap, before any token is spent).
|
|
229
|
+
try:
|
|
230
|
+
candidate = validate_slug(slug)
|
|
231
|
+
except SlugRefused as refused:
|
|
232
|
+
reason, status = _SLUG_REASON_STATUS[refused.reason]
|
|
233
|
+
return _refuse(
|
|
234
|
+
SignupState.GOOGLE_VERIFIED,
|
|
235
|
+
reason,
|
|
236
|
+
str(refused),
|
|
237
|
+
status,
|
|
238
|
+
google_verified=google_verified,
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
# 5. human_verified: server-side siteverify, then spend the token once.
|
|
242
|
+
if not turnstile_token:
|
|
243
|
+
return _refuse(
|
|
244
|
+
SignupState.GOOGLE_VERIFIED,
|
|
245
|
+
SignupReason.TURNSTILE_MISSING,
|
|
246
|
+
"Complete the human verification challenge.",
|
|
247
|
+
403,
|
|
248
|
+
google_verified=google_verified,
|
|
249
|
+
)
|
|
250
|
+
result = self.verifier(
|
|
251
|
+
secret=config.turnstile_secret_key,
|
|
252
|
+
token=turnstile_token,
|
|
253
|
+
remote_ip=client_ip,
|
|
254
|
+
expected_hostname=config.turnstile_expected_hostname,
|
|
255
|
+
)
|
|
256
|
+
if not result.success:
|
|
257
|
+
return _refuse(
|
|
258
|
+
SignupState.GOOGLE_VERIFIED,
|
|
259
|
+
SignupReason.TURNSTILE_FAILED,
|
|
260
|
+
"Human verification failed. Reload the page and try again.",
|
|
261
|
+
403,
|
|
262
|
+
google_verified=google_verified,
|
|
263
|
+
)
|
|
264
|
+
if not store.consume_turnstile_token(
|
|
265
|
+
token=turnstile_token,
|
|
266
|
+
identity_id=identity.get("identity_id"),
|
|
267
|
+
client_ip=client_ip,
|
|
268
|
+
hostname=result.hostname,
|
|
269
|
+
now=now,
|
|
270
|
+
):
|
|
271
|
+
return _refuse(
|
|
272
|
+
SignupState.HUMAN_VERIFIED,
|
|
273
|
+
SignupReason.TURNSTILE_REPLAYED,
|
|
274
|
+
"That verification token was already used. Complete the challenge again.",
|
|
275
|
+
403,
|
|
276
|
+
google_verified=google_verified,
|
|
277
|
+
)
|
|
278
|
+
human_verified = True
|
|
279
|
+
|
|
280
|
+
# 5b. Idempotent repeat: this identity already requested this slug. The
|
|
281
|
+
# answer is the existing row and nothing is written, so it is given
|
|
282
|
+
# before the caps — which a repeat would otherwise trip by definition.
|
|
283
|
+
already = store.eligibility_by_subject_slug(identity["subject"], candidate)
|
|
284
|
+
if already is not None:
|
|
285
|
+
message = {
|
|
286
|
+
"active": "Your workspace is ready.",
|
|
287
|
+
"provisioning": "Your workspace is being created.",
|
|
288
|
+
"failed": "Your workspace request needs attention.",
|
|
289
|
+
}.get(str(already.get("status") or ""),
|
|
290
|
+
"Your workspace request was already queued.")
|
|
291
|
+
return SignupDecision(
|
|
292
|
+
state=SignupState.ELIGIBLE,
|
|
293
|
+
reason=None,
|
|
294
|
+
message=message,
|
|
295
|
+
status_code=200,
|
|
296
|
+
google_verified=google_verified,
|
|
297
|
+
human_verified=human_verified,
|
|
298
|
+
eligibility=already,
|
|
299
|
+
created=False,
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
# 6. Mode=invite: the address must have an open invitation.
|
|
303
|
+
invite = None
|
|
304
|
+
if config.mode == "invite":
|
|
305
|
+
invite = store.active_invite_for(identity.get("email") or "", now=now)
|
|
306
|
+
if invite is None:
|
|
307
|
+
return _refuse(
|
|
308
|
+
SignupState.HUMAN_VERIFIED,
|
|
309
|
+
SignupReason.INVITE_REQUIRED,
|
|
310
|
+
"Hoja is invite-only right now. Ask for an invitation for this address.",
|
|
311
|
+
403,
|
|
312
|
+
google_verified=google_verified,
|
|
313
|
+
human_verified=human_verified,
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
# 7. Caps: per identity (one workspace per Google account) and per IP.
|
|
317
|
+
if store.eligibility_count(google_sub=identity["subject"]) >= config.identity_cap:
|
|
318
|
+
return _refuse(
|
|
319
|
+
SignupState.HUMAN_VERIFIED,
|
|
320
|
+
SignupReason.IDENTITY_CAP_EXCEEDED,
|
|
321
|
+
"This Google account has already requested its workspace.",
|
|
322
|
+
429,
|
|
323
|
+
google_verified=google_verified,
|
|
324
|
+
human_verified=human_verified,
|
|
325
|
+
)
|
|
326
|
+
since = now - timedelta(seconds=config.ip_window_seconds)
|
|
327
|
+
if (
|
|
328
|
+
client_ip
|
|
329
|
+
and store.eligibility_count(client_ip=client_ip, since=since) >= config.ip_cap
|
|
330
|
+
):
|
|
331
|
+
return _refuse(
|
|
332
|
+
SignupState.HUMAN_VERIFIED,
|
|
333
|
+
SignupReason.IP_CAP_EXCEEDED,
|
|
334
|
+
"Too many workspaces requested from this network recently. Try again later.",
|
|
335
|
+
429,
|
|
336
|
+
google_verified=google_verified,
|
|
337
|
+
human_verified=human_verified,
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
# 8. Is the name free? Any queued request or provisioned tenant claims it.
|
|
341
|
+
if candidate in store.taken_slugs(config.tenant_registry):
|
|
342
|
+
return _refuse(
|
|
343
|
+
SignupState.HUMAN_VERIFIED,
|
|
344
|
+
SignupReason.SLUG_TAKEN,
|
|
345
|
+
f"{candidate!r} is already taken. Pick another name.",
|
|
346
|
+
409,
|
|
347
|
+
google_verified=google_verified,
|
|
348
|
+
human_verified=human_verified,
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
# 9. eligible: record the request. Nothing is provisioned here.
|
|
352
|
+
try:
|
|
353
|
+
row, created = store.record_eligibility(
|
|
354
|
+
identity=identity,
|
|
355
|
+
slug=candidate,
|
|
356
|
+
client_ip=client_ip or "unknown",
|
|
357
|
+
turnstile_hostname=result.hostname,
|
|
358
|
+
now=now,
|
|
359
|
+
)
|
|
360
|
+
except EligibilityConflict as conflict:
|
|
361
|
+
reason = (
|
|
362
|
+
SignupReason.SLUG_TAKEN
|
|
363
|
+
if conflict.reason == "slug_taken"
|
|
364
|
+
else SignupReason.NOT_AUTHENTICATED
|
|
365
|
+
)
|
|
366
|
+
return _refuse(
|
|
367
|
+
SignupState.HUMAN_VERIFIED,
|
|
368
|
+
reason,
|
|
369
|
+
str(conflict),
|
|
370
|
+
409,
|
|
371
|
+
google_verified=google_verified,
|
|
372
|
+
human_verified=human_verified,
|
|
373
|
+
)
|
|
374
|
+
if invite is not None:
|
|
375
|
+
store.consume_invite(
|
|
376
|
+
invite["id"],
|
|
377
|
+
identity.get("identity_id") or identity["id"],
|
|
378
|
+
now=now,
|
|
379
|
+
)
|
|
380
|
+
return SignupDecision(
|
|
381
|
+
state=SignupState.ELIGIBLE,
|
|
382
|
+
reason=None,
|
|
383
|
+
message=(
|
|
384
|
+
"Your workspace request is queued."
|
|
385
|
+
if created
|
|
386
|
+
else "Your workspace request was already queued."
|
|
387
|
+
),
|
|
388
|
+
status_code=201 if created else 200,
|
|
389
|
+
google_verified=google_verified,
|
|
390
|
+
human_verified=human_verified,
|
|
391
|
+
eligibility=row,
|
|
392
|
+
created=created,
|
|
393
|
+
)
|