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
hoja_server/sync.py ADDED
@@ -0,0 +1,249 @@
1
+ """Compact browser sync: one bootstrap snapshot plus seq-based deltas.
2
+
3
+ The browser used to page issues 100 at a time through GraphQL and refetch the
4
+ whole dashboard on every change event. This module serves:
5
+
6
+ - ``bootstrap``: every open issue plus issues closed within ``closed_days``,
7
+ in a columnar (header + row arrays) shape, alongside the small workspace
8
+ metadata the shell needs. The response carries the org change ``seq`` and a
9
+ validator so an unchanged snapshot revalidates as a bodyless 304.
10
+ - ``delta``: the issue rows touched after a seq, ids that disappeared, and
11
+ fresh metadata only when a metadata entity changed.
12
+
13
+ Issue rows are normalized (ids, not nested objects); the client hydrates them
14
+ against the metadata it already holds.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import asyncio
19
+ import hashlib
20
+ from collections import OrderedDict
21
+ from collections.abc import Awaitable, Callable
22
+ from datetime import datetime, timedelta, timezone
23
+
24
+ from sqlalchemy import and_, or_, select
25
+
26
+ from hoja_server.db import (
27
+ issue,
28
+ issue_label_link,
29
+ issue_subscriber,
30
+ user,
31
+ workflow_state,
32
+ )
33
+ from hoja_server.store import Store, visible_team_clause
34
+
35
+ SYNC_VERSION = 1
36
+ DEFAULT_CLOSED_DAYS = 14
37
+ MAX_CLOSED_DAYS = 365
38
+ # A client further behind than this re-bootstraps instead of replaying.
39
+ MAX_DELTA_EVENTS = 5000
40
+
41
+ ISSUE_COLUMNS = (
42
+ "id", "identifier", "title", "priority", "estimate", "createdAt", "updatedAt",
43
+ "stateChangedAt", "dueDate", "stateId", "teamId", "projectId", "assigneeId",
44
+ "creatorId", "cycleId", "parentId", "labelIds", "subscriberIds",
45
+ )
46
+ TEAM_COLUMN = ISSUE_COLUMNS.index("teamId")
47
+ _CLOSED_TYPES = ("completed", "canceled")
48
+ # Entities whose change invalidates the metadata block rather than issue rows.
49
+ META_ENTITIES = {"team", "teamMember", "workflowState", "label", "cycle", "project", "user", "member"}
50
+ # Entities that change who can see which issues; a delta cannot express that.
51
+ RELOAD_ENTITIES = {"team", "teamMember"}
52
+
53
+ META_QUERY = """query SyncMeta {
54
+ viewer { id name email admin }
55
+ workspace { id name urlKey }
56
+ teams { nodes { id name key description states { nodes { id name color type } }
57
+ members { nodes { id name email } } activeCycle { id name number startsAt endsAt progress } } }
58
+ projects(first: 250) { nodes { id name description state progress startDate targetDate health
59
+ lead { name } teams { nodes { id name key } } } pageInfo { hasNextPage endCursor } }
60
+ cycles(first: 250) { nodes { id name number startsAt endsAt completedAt progress team { id name key } } }
61
+ issueLabels(first: 250) { nodes { id name color } }
62
+ }"""
63
+
64
+
65
+ class SingleFlightCache:
66
+ """Small LRU whose misses are built once even when many requests miss together.
67
+
68
+ Python's sqlite3 driver re-acquires the GIL per fetched row, so N threads
69
+ reading the same snapshot run far slower than one; sharing the build keeps a
70
+ burst of page loads at the cost of a single query.
71
+ """
72
+
73
+ def __init__(self, max_entries: int) -> None:
74
+ self.max_entries = max_entries
75
+ self._entries: OrderedDict = OrderedDict()
76
+ self._inflight: dict = {}
77
+
78
+ async def get(self, key, build: Callable[[], Awaitable]):
79
+ if key in self._entries:
80
+ self._entries.move_to_end(key)
81
+ return self._entries[key]
82
+ pending = self._inflight.get(key)
83
+ if pending is not None:
84
+ return await asyncio.shield(pending)
85
+ future = asyncio.get_running_loop().create_future()
86
+ self._inflight[key] = future
87
+ try:
88
+ value = await build()
89
+ except BaseException as exc:
90
+ future.set_exception(exc)
91
+ future.exception() # mark retrieved when nobody else was waiting
92
+ raise
93
+ finally:
94
+ self._inflight.pop(key, None)
95
+ future.set_result(value)
96
+ self._entries[key] = value
97
+ while len(self._entries) > self.max_entries:
98
+ self._entries.popitem(last=False)
99
+ return value
100
+
101
+
102
+ def closed_cutoff(closed_days: int, now: datetime | None = None) -> str:
103
+ """Day-granular ISO date; issue timestamps compare lexicographically against it."""
104
+ now = now or datetime.now(timezone.utc)
105
+ return (now - timedelta(days=closed_days)).date().isoformat()
106
+
107
+
108
+ def sync_scope(org_id: str, viewer_id: str) -> str:
109
+ """Opaque identity of a snapshot's owner; a delta for another scope must re-bootstrap."""
110
+ return hashlib.sha256(f"{org_id}|{viewer_id}".encode()).hexdigest()[:16]
111
+
112
+
113
+ def org_users(store: Store, org_id: str) -> list[list]:
114
+ """[id, name] for every profile in the org, so creators and assignees always resolve."""
115
+ with store.engine.connect() as conn:
116
+ return [list(r) for r in conn.execute(select(user.c.id, user.c.name)
117
+ .where(user.c.organization_id == org_id))]
118
+
119
+
120
+ def _visibility_key(visible: frozenset | None) -> str:
121
+ if visible is None:
122
+ return "*"
123
+ return hashlib.sha256(",".join(sorted(visible)).encode()).hexdigest()[:16]
124
+
125
+
126
+ def issues_key(org_id: str, seq: int, cutoff: str, visible: frozenset | None) -> tuple:
127
+ """Issue rows depend only on these, so viewers with equal visibility share them."""
128
+ return (org_id, seq, cutoff, _visibility_key(visible))
129
+
130
+
131
+ def snapshot_etag(viewer_id: str, key: tuple) -> str:
132
+ """Validator for a bootstrap: changes whenever any captured row, visibility or window changes."""
133
+ raw = f"v{SYNC_VERSION}|{viewer_id}|" + "|".join(map(str, key))
134
+ return '"' + hashlib.sha256(raw.encode()).hexdigest()[:32] + '"'
135
+
136
+
137
+ def _issue_select(conn, org_id: str, viewer_id: str | None):
138
+ stmt = (
139
+ select(
140
+ issue.c.id, issue.c.identifier, issue.c.title, issue.c.priority, issue.c.estimate,
141
+ issue.c.created_at, issue.c.updated_at, issue.c.state_changed_at, issue.c.due_date,
142
+ issue.c.state_id, issue.c.team_id, issue.c.project_id, issue.c.assignee_id,
143
+ issue.c.creator_id, issue.c.cycle_id, issue.c.parent_id,
144
+ )
145
+ .select_from(issue.outerjoin(workflow_state, workflow_state.c.id == issue.c.state_id))
146
+ .where(and_(issue.c.organization_id == org_id, issue.c.archived_at.is_(None)))
147
+ )
148
+ if viewer_id is None:
149
+ return stmt # unscoped: callers filter rows by teamId per viewer themselves
150
+ clause = visible_team_clause(conn, org_id, viewer_id, issue.c.team_id)
151
+ return stmt if clause is None else stmt.where(clause)
152
+
153
+
154
+ def _rows_with_links(conn, stmt) -> list[list]:
155
+ rows = conn.execute(stmt.order_by(issue.c.updated_at.desc(), issue.c.id.desc())).all()
156
+ if not rows:
157
+ return []
158
+ ids = stmt.with_only_columns(issue.c.id).order_by(None).subquery()
159
+ labels: dict[str, list[str]] = {}
160
+ for iid, lid in conn.execute(select(issue_label_link.c.issue_id, issue_label_link.c.label_id)
161
+ .where(issue_label_link.c.issue_id.in_(select(ids.c.id)))):
162
+ labels.setdefault(iid, []).append(lid)
163
+ subs: dict[str, list[str]] = {}
164
+ for iid, uid in conn.execute(select(issue_subscriber.c.issue_id, issue_subscriber.c.user_id)
165
+ .where(issue_subscriber.c.issue_id.in_(select(ids.c.id)))):
166
+ subs.setdefault(iid, []).append(uid)
167
+ return [[*row, labels.get(row[0], []), subs.get(row[0], [])] for row in rows]
168
+
169
+
170
+ def bootstrap_issues(store: Store, org_id: str, viewer_id: str, cutoff: str) -> list[list]:
171
+ with store.engine.connect() as conn:
172
+ stmt = _issue_select(conn, org_id, viewer_id).where(or_(
173
+ workflow_state.c.type.is_(None),
174
+ workflow_state.c.type.not_in(_CLOSED_TYPES),
175
+ issue.c.updated_at >= cutoff,
176
+ ))
177
+ return _rows_with_links(conn, stmt)
178
+
179
+
180
+ def issues_by_id(store: Store, org_id: str, viewer_id: str | None, ids: list[str]) -> list[list]:
181
+ """Rows for ids; viewer_id=None returns them unscoped (the caller must filter by teamId)."""
182
+ out: list[list] = []
183
+ with store.engine.connect() as conn:
184
+ # Chunked to stay under SQLite's bound-parameter limit.
185
+ for start in range(0, len(ids), 500):
186
+ chunk = ids[start:start + 500]
187
+ out.extend(_rows_with_links(conn, _issue_select(conn, org_id, viewer_id)
188
+ .where(issue.c.id.in_(chunk))))
189
+ return out
190
+
191
+
192
+ def row_visible(row: list, visible: frozenset | None) -> bool:
193
+ """Issue visibility is team visibility; None means unrestricted (admin)."""
194
+ return visible is None or row[TEAM_COLUMN] in visible
195
+
196
+
197
+ def build_delta(store: Store, org_id: str, viewer_id: str, after: int, scope: str | None = None) -> dict:
198
+ """Changes after ``after``; ``reload`` tells the client to re-bootstrap instead."""
199
+ latest = store.latest_change_seq(org_id)
200
+ if after > latest or (scope is not None and scope != sync_scope(org_id, viewer_id)):
201
+ return {"v": SYNC_VERSION, "reload": True, "seq": latest}
202
+ events = store.change_events_after(org_id, after, limit=MAX_DELTA_EVENTS + 1, viewer_id=viewer_id)
203
+ if len(events) > MAX_DELTA_EVENTS:
204
+ return {"v": SYNC_VERSION, "reload": True, "seq": latest}
205
+ entities = {e["entity"] for e in events}
206
+ if entities & RELOAD_ENTITIES:
207
+ return {"v": SYNC_VERSION, "reload": True, "seq": latest}
208
+ touched = list(dict.fromkeys(e["entityId"] for e in events if e["entity"] == "issue"))
209
+ rows = issues_by_id(store, org_id, viewer_id, touched) if touched else []
210
+ present = {r[0] for r in rows}
211
+ return {
212
+ "v": SYNC_VERSION,
213
+ "reload": False,
214
+ # Invisible events still advance the cursor: everything up to latest was considered.
215
+ "seq": max([latest] + [e["seq"] for e in events]),
216
+ "columns": ISSUE_COLUMNS,
217
+ "issues": rows,
218
+ "removed": [i for i in touched if i not in present],
219
+ "meta": bool(entities & META_ENTITIES),
220
+ "other": sorted(entities - META_ENTITIES - {"issue"}),
221
+ }
222
+
223
+
224
+ STATE_COLUMN = ISSUE_COLUMNS.index("stateId")
225
+ UPDATED_COLUMN = ISSUE_COLUMNS.index("updatedAt")
226
+
227
+
228
+ def closed_state_ids(store: Store, org_id: str) -> frozenset:
229
+ with store.engine.connect() as conn:
230
+ return frozenset(r[0] for r in conn.execute(select(workflow_state.c.id).where(and_(
231
+ workflow_state.c.organization_id == org_id, workflow_state.c.type.in_(_CLOSED_TYPES)))))
232
+
233
+
234
+ def derive_issues(prev_rows: list[list], changes: dict, visible: frozenset | None, cutoff: str,
235
+ closed_states: frozenset) -> list[list]:
236
+ """A newer bootstrap issue list from an older one plus the changed rows (None = gone).
237
+
238
+ Applies the same window and visibility rules as bootstrap_issues, so a page
239
+ load during a burst of writes costs a merge instead of re-reading every row.
240
+ """
241
+ out = [r for r in prev_rows if r[0] not in changes]
242
+ for row in changes.values():
243
+ if row is None or not row_visible(row, visible):
244
+ continue
245
+ if row[STATE_COLUMN] in closed_states and (row[UPDATED_COLUMN] or "") < cutoff:
246
+ continue
247
+ out.append(row)
248
+ out.sort(key=lambda r: (r[UPDATED_COLUMN] or "", r[0]), reverse=True)
249
+ return out
@@ -0,0 +1,131 @@
1
+ """Per-transaction tenant context for PostgreSQL row-level security.
2
+
3
+ Every transaction on a PostgreSQL engine starts with
4
+
5
+ SELECT set_config('hoja.org_id', <org or ''>, true),
6
+ set_config('hoja.system', <'on' or ''>, true)
7
+
8
+ The third argument makes both settings transaction-local (``SET LOCAL``): they
9
+ vanish at COMMIT or ROLLBACK, so a pooled connection can never carry one
10
+ request's tenant into the next. This is the pattern PostgREST uses for request
11
+ claims. Deployments without row-level security policies are unaffected; the
12
+ settings are simply never read.
13
+
14
+ Context sources:
15
+
16
+ - ``bind(org)``: once a request has authenticated, for the rest of that request.
17
+ - ``system()``: an explicit, enumerated cross-tenant path (credential lookups
18
+ before a tenant is known, realtime fan-out, background loops).
19
+ - neither: no tenant. Under row-level security that reads as no rows (fail closed).
20
+
21
+ Both live in ContextVars, so they follow a request through awaits and into
22
+ Starlette's thread pool, and never leak across requests (each runs in its own
23
+ task with its own context copy).
24
+
25
+ A context set inside a worker thread does NOT come back: whoever authenticates
26
+ with ``run_in_threadpool(auth, ...)`` must ``bind`` after it returns.
27
+
28
+ Gate: ``HOJA_TEST_RLS=1 HOJA_TEST_POSTGRES_URL=... pytest tests/test_meetings.py
29
+ tests/test_meetings_social.py tests/test_agent_chat.py tests/test_agent_durable.py tests/e2e``
30
+ runs those suites with the app as a restricted role under the production
31
+ policies (see tests/rls_mode.py).
32
+ """
33
+ from __future__ import annotations
34
+
35
+ from contextlib import contextmanager
36
+ from contextvars import ContextVar
37
+ from typing import Any, Awaitable, Iterator, TypeVar
38
+
39
+ from sqlalchemy import event
40
+ from sqlalchemy.engine import Engine
41
+
42
+ T = TypeVar("T")
43
+
44
+ _org: ContextVar[str | None] = ContextVar("hoja_tenant_org", default=None)
45
+ _system: ContextVar[bool] = ContextVar("hoja_tenant_system", default=False)
46
+
47
+ # Paths that run before a tenant is known, or that are tenant-agnostic by
48
+ # nature. They see every row, exactly as before row-level security. Keep this
49
+ # list short and reviewed: anything not matched fails closed until _auth binds.
50
+ SYSTEM_PATH_PREFIXES = (
51
+ "/auth/", # login, setup, invite accept, workspaces, Google, me/logout
52
+ "/onboarding/", # first-run status and bootstrap
53
+ "/api/signup", # pre-tenant sign-up (global tables)
54
+ "/.well-known/", # OAuth discovery
55
+ "/mcp/authorize", "/mcp/token", "/mcp/register", "/mcp/revoke", "/mcp/oauth/",
56
+ )
57
+ SYSTEM_PATHS = frozenset({"/health", "/ready"})
58
+
59
+ _SET = "SELECT set_config('hoja.org_id', %s, true), set_config('hoja.system', %s, true)"
60
+
61
+
62
+ def bind(org: str | None) -> None:
63
+ """Scope the rest of the current context (one request) to ``org``."""
64
+ _org.set(org or None)
65
+
66
+
67
+ def enter_system() -> None:
68
+ """Mark the rest of the current context (one request) as a system path.
69
+
70
+ For requests whose credential is not a tenant member: a meeting guest token
71
+ or a public meeting code. The service's own predicates scope those queries.
72
+ """
73
+ _system.set(True)
74
+
75
+
76
+ def current() -> tuple[str | None, bool]:
77
+ return _org.get(), _system.get()
78
+
79
+
80
+ @contextmanager
81
+ def system() -> Iterator[None]:
82
+ """Run an enumerated cross-tenant operation."""
83
+ token = _system.set(True)
84
+ try:
85
+ yield
86
+ finally:
87
+ _system.reset(token)
88
+
89
+
90
+ async def as_system(awaitable: Awaitable[T]) -> T:
91
+ """Await ``awaitable`` in system context; for tasks that serve every tenant."""
92
+ _system.set(True) # this coroutine runs in its own task's context copy
93
+ return await awaitable
94
+
95
+
96
+ def is_system_path(path: str) -> bool:
97
+ return path in SYSTEM_PATHS or path.startswith(SYSTEM_PATH_PREFIXES)
98
+
99
+
100
+ def install(engine: Engine) -> None:
101
+ """Prefix every PostgreSQL transaction with the transaction-local settings."""
102
+ if engine.dialect.name != "postgresql":
103
+ return
104
+
105
+ @event.listens_for(engine, "begin")
106
+ def _set_tenant(conn: Any) -> None:
107
+ org, sys_ = current()
108
+ # The raw DBAPI cursor: psycopg opens the transaction implicitly on this
109
+ # first statement, so the settings are local to exactly this transaction.
110
+ cursor = conn.connection.dbapi_connection.cursor()
111
+ try:
112
+ cursor.execute(_SET, (org or "", "on" if sys_ else ""))
113
+ finally:
114
+ cursor.close()
115
+
116
+
117
+ class TenantContextMiddleware:
118
+ """ASGI: run the enumerated system paths in system context; leave the rest empty."""
119
+
120
+ def __init__(self, app: Any) -> None:
121
+ self.app = app
122
+
123
+ async def __call__(self, scope: dict, receive: Any, send: Any) -> None:
124
+ if scope["type"] in ("http", "websocket") and is_system_path(scope.get("path", "")):
125
+ token = _system.set(True)
126
+ try:
127
+ await self.app(scope, receive, send)
128
+ finally:
129
+ _system.reset(token)
130
+ return
131
+ await self.app(scope, receive, send)
@@ -0,0 +1,81 @@
1
+ """Server-side Turnstile verification — the *human* layer, separate from identity.
2
+
3
+ Two things this module refuses to do:
4
+
5
+ * trust a client-side success flag (the token is always presented to
6
+ ``siteverify`` from the server, with the secret and the client's address), and
7
+ * accept a token whose ``hostname`` is not the one we expect.
8
+
9
+ The siteverify API has no hostname *input* parameter, so "expected hostname" is
10
+ enforced on the response: Cloudflare echoes the hostname the widget was served
11
+ from, and a token minted for another site is refused here. Single use is
12
+ enforced in the database (``turnstile_use``) *and* by Cloudflare itself, which
13
+ answers ``timeout-or-duplicate`` for a token it has already seen.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass, field
19
+ from typing import Any
20
+
21
+ SITEVERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class TurnstileResult:
26
+ """Outcome of one siteverify call. ``reason`` is stable for logging/tests."""
27
+
28
+ success: bool
29
+ reason: str
30
+ hostname: str | None = None
31
+ error_codes: tuple[str, ...] = ()
32
+ raw: dict[str, Any] = field(default_factory=dict)
33
+
34
+
35
+ def _http_post_form(url: str, data: dict[str, str], *, timeout: float) -> dict[str, Any]:
36
+ """The single outbound POST seam. Tests replace it; nothing else may call out."""
37
+ import httpx
38
+
39
+ response = httpx.post(url, data=data, timeout=timeout)
40
+ document = response.json()
41
+ if not isinstance(document, dict):
42
+ raise ValueError("siteverify returned a non-object")
43
+ return document
44
+
45
+
46
+ def verify_turnstile(
47
+ *,
48
+ secret: str,
49
+ token: str,
50
+ remote_ip: str | None,
51
+ expected_hostname: str,
52
+ expected_action: str | None = None,
53
+ timeout: float = 8.0,
54
+ ) -> TurnstileResult:
55
+ """Verify one token with Cloudflare. Never raises on a refusal."""
56
+ if not secret:
57
+ return TurnstileResult(False, "not_configured")
58
+ if not token or not isinstance(token, str):
59
+ return TurnstileResult(False, "missing_token")
60
+
61
+ payload = {"secret": secret, "response": token}
62
+ if remote_ip:
63
+ payload["remoteip"] = remote_ip
64
+ try:
65
+ document = _http_post_form(SITEVERIFY_URL, payload, timeout=timeout)
66
+ except Exception as exc: # network, TLS, JSON: fail closed, never open
67
+ return TurnstileResult(False, "network_error", raw={"error": str(exc)})
68
+
69
+ raw_codes = document.get("error-codes") or []
70
+ codes = tuple(str(code) for code in raw_codes) if isinstance(raw_codes, list) else ()
71
+ hostname = document.get("hostname")
72
+ hostname = hostname.lower() if isinstance(hostname, str) else None
73
+
74
+ if document.get("success") is not True:
75
+ return TurnstileResult(False, "verification_failed", hostname, codes, document)
76
+ if hostname != (expected_hostname or "").lower():
77
+ return TurnstileResult(False, "hostname_mismatch", hostname, codes, document)
78
+ action = document.get("action")
79
+ if expected_action and action != expected_action:
80
+ return TurnstileResult(False, "action_mismatch", hostname, codes, document)
81
+ return TurnstileResult(True, "ok", hostname, codes, document)