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/app.py ADDED
@@ -0,0 +1,2189 @@
1
+ """FastAPI + Ariadne ASGI app with token auth middleware.
2
+
3
+ - POST /graphql : the Linear-compatible endpoint the CLI talks to.
4
+ - Auth: raw token in Authorization header (with or without 'Bearer').
5
+ Unknown/revoked token → HTTP 401 + {errors:[{message}]}.
6
+ - Never emits 429. GraphQL errors → HTTP 200 + {errors:[...], data:null}.
7
+ - Optional OFFLINE mode: if HOJA_SERVER_OPEN=1, any token maps to the only
8
+ seeded identity in an unambiguous SQLite database.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import gzip
15
+ import ipaddress
16
+ import json
17
+ import logging
18
+ import os
19
+ import secrets
20
+ import time
21
+ from contextlib import asynccontextmanager
22
+ from datetime import datetime, timedelta, timezone
23
+ from pathlib import Path
24
+ from urllib.parse import quote, urlsplit
25
+
26
+ from ariadne import format_error, graphql, graphql_sync
27
+ from graphql import (
28
+ FieldNode,
29
+ FragmentDefinitionNode,
30
+ FragmentSpreadNode,
31
+ GraphQLError,
32
+ InlineFragmentNode,
33
+ OperationDefinitionNode,
34
+ parse,
35
+ )
36
+ from sqlalchemy import select, text
37
+ from starlette.applications import Starlette
38
+ from starlette.datastructures import MutableHeaders
39
+ from starlette.middleware.gzip import GZipMiddleware
40
+ from starlette.requests import Request
41
+ from starlette.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
42
+ from starlette.routing import Route, WebSocketRoute
43
+ from starlette.concurrency import run_in_threadpool
44
+ from starlette.websockets import WebSocket
45
+
46
+ from hoja_server.cloudflare_realtime import CloudflareRealtime
47
+ from hoja_server.connectors_api import connector_binding_for, connector_routes
48
+ from hoja_server.db import (
49
+ _seed_demo_issues,
50
+ api_key,
51
+ browser_session,
52
+ gen_session_token,
53
+ gen_token,
54
+ global_identity,
55
+ identity_credential,
56
+ make_engine,
57
+ new_id,
58
+ now_iso,
59
+ organization,
60
+ organization_membership,
61
+ password_credential,
62
+ rate_limit_blocked,
63
+ rate_limit_record,
64
+ resolve_database_target,
65
+ resolve_token_identity,
66
+ schema_is_current,
67
+ seed_states_for_team,
68
+ team,
69
+ team_member,
70
+ token_hash,
71
+ user,
72
+ )
73
+ from hoja_server.denials import DENY_HINT, hint_for
74
+ from hoja_server.deployment import single_org_mode
75
+ from hoja_server.meetings import MeetingService
76
+ from hoja_server.meetings_api import MeetingHub, meeting_routes
77
+ from hoja_server.resolvers import build_schema
78
+ from hoja_server.secrets_box import SecretBoxError
79
+ from hoja_server import google_login, identity_transfer, google_oidc
80
+ from hoja_server.signup_config import (
81
+ TURNSTILE_SCRIPT_URL,
82
+ SignupConfigError,
83
+ load_signup_config,
84
+ )
85
+ from hoja_server.signup_gate import (
86
+ CROSS_SITE_REQUEST,
87
+ INVALID_REQUEST,
88
+ SignupGate,
89
+ )
90
+ from hoja_server.signup_store import SignupStore
91
+ from hoja_server.store import Store
92
+ from hoja_server import tenant_context
93
+ from hoja_server import realtime, sync
94
+ from hoja_server.writer import Writer
95
+
96
+ _schema = build_schema()
97
+ _WEB_ROOT = Path(
98
+ os.environ.get("HOJA_WEB_ROOT", Path(__file__).resolve().parent.parent / "frontend" / "dist")
99
+ )
100
+
101
+
102
+ # Content-hashed brand mark: the URL changes with the bytes, so CDN caches cannot pin an old response.
103
+ BRAND_MARK = "hoja-clover.8371400e.svg"
104
+
105
+
106
+ def _first_identity(engine):
107
+ """Offline convenience for an unambiguous isolated SQLite database."""
108
+ if engine.dialect.name != "sqlite":
109
+ return None, None
110
+ try:
111
+ return resolve_token_identity(engine)
112
+ except ValueError:
113
+ return None, None
114
+
115
+
116
+ def _valid_public_host(value: str) -> bool:
117
+ """Accept configured DNS names/IP literals, but not URL syntax or userinfo."""
118
+ import re
119
+ from urllib.parse import urlsplit
120
+
121
+ candidate = value.strip()
122
+ if not candidate or any(ch in candidate for ch in "/\\@?#"):
123
+ return False
124
+ parsed = urlsplit("//" + candidate)
125
+ if not parsed.hostname or parsed.path or parsed.query or parsed.fragment:
126
+ return False
127
+ try:
128
+ ipaddress.ip_address(parsed.hostname)
129
+ return True
130
+ except ValueError:
131
+ labels = parsed.hostname.rstrip(".").split(".")
132
+ return len(parsed.hostname) <= 253 and all(
133
+ re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?", label)
134
+ for label in labels
135
+ )
136
+
137
+
138
+ _MAX_SEQ = 2**63 - 1
139
+ _MAX_GRAPHQL_BODY = 1_000_000
140
+ _MAX_QUERY_DEPTH = 15
141
+ _MAX_QUERY_FIELDS = 100
142
+ _MAX_QUERY_VISITS = 10_000
143
+ # Read-only sync endpoints reuse a resolved credential this long (matches the
144
+ # realtime socket revalidation interval) instead of re-querying it per request.
145
+ _SYNC_AUTH_TTL = 5.0
146
+ _LOGIN_FAILURE_LIMIT = 10
147
+ _LOGIN_FAILURE_WINDOW_SECONDS = 15 * 60
148
+ _CSP_HTML = "frame-ancestors 'none'; object-src 'none'; base-uri 'self'"
149
+
150
+ # Served when the SPA bundle is absent. It is HTML on purpose: the security-headers
151
+ # middleware only attaches Content-Security-Policy to text/html responses, and a
152
+ # browser hitting an unbuilt deployment must still get clickjacking protection.
153
+ _UNBUILT_HTML = (
154
+ '<!doctype html><html lang="en"><head><meta charset="utf-8">'
155
+ "<title>Hoja</title></head><body><h1>Web UI has not been built</h1>"
156
+ "<p>Run <code>npm run build</code> in <code>frontend/</code>, or point "
157
+ "<code>HOJA_WEB_ROOT</code> at a built bundle.</p></body></html>"
158
+ )
159
+ _graphql_log = logging.getLogger("hoja_server.graphql")
160
+ _security_log = logging.getLogger("hoja_server.security")
161
+
162
+
163
+ def _bad_request(message: str) -> JSONResponse:
164
+ return JSONResponse(
165
+ {"errors": [{"message": message, "extensions": {"code": "BAD_REQUEST"}}]}, status_code=400
166
+ )
167
+
168
+
169
+ def _too_large() -> JSONResponse:
170
+ return JSONResponse(
171
+ {"errors": [{"message": "Request body is too large.", "extensions": {"code": "PAYLOAD_TOO_LARGE"}}]},
172
+ status_code=413,
173
+ )
174
+
175
+
176
+ def _query_problem(query: str) -> str | None:
177
+ """Return a user-facing rejection for over-deep or over-wide documents, else None."""
178
+ try:
179
+ document = parse(query)
180
+ except GraphQLError:
181
+ return None # syntax errors are reported by graphql() itself
182
+ except RecursionError:
183
+ return "Query is nested too deeply."
184
+ fragments = {d.name.value: d for d in document.definitions if isinstance(d, FragmentDefinitionNode)}
185
+ counts = {"aliases": 0, "deepest": 0, "visits": 0}
186
+
187
+ def walk(selection_set, depth, spreads):
188
+ counts["deepest"] = max(counts["deepest"], depth)
189
+ for selection in selection_set.selections:
190
+ counts["visits"] += 1
191
+ if isinstance(selection, FieldNode):
192
+ if selection.alias:
193
+ counts["aliases"] += 1
194
+ if selection.selection_set:
195
+ walk(selection.selection_set, depth + 1, spreads)
196
+ elif isinstance(selection, InlineFragmentNode):
197
+ walk(selection.selection_set, depth, spreads)
198
+ elif isinstance(selection, FragmentSpreadNode):
199
+ name = selection.name.value
200
+ if name in fragments and name not in spreads:
201
+ walk(fragments[name].selection_set, depth, spreads | {name})
202
+
203
+ roots = 0
204
+ for definition in document.definitions:
205
+ if isinstance(definition, OperationDefinitionNode):
206
+ roots += sum(isinstance(s, FieldNode) for s in definition.selection_set.selections)
207
+ walk(definition.selection_set, 1, frozenset())
208
+ if counts["deepest"] > _MAX_QUERY_DEPTH:
209
+ return f"Query depth exceeds {_MAX_QUERY_DEPTH}."
210
+ if roots > _MAX_QUERY_FIELDS or counts["aliases"] > _MAX_QUERY_FIELDS:
211
+ return f"Query exceeds {_MAX_QUERY_FIELDS} root fields or aliases."
212
+ if counts["visits"] > _MAX_QUERY_VISITS:
213
+ return "Query is too complex."
214
+ return None
215
+
216
+
217
+ async def _read_json_object(request: Request, limit: int):
218
+ declared = request.headers.get("content-length")
219
+ if declared is not None:
220
+ if not declared.isdigit():
221
+ return None, _bad_request("Invalid Content-Length.")
222
+ if int(declared) > limit:
223
+ return None, _too_large()
224
+ body = bytearray()
225
+ async for chunk in request.stream():
226
+ body.extend(chunk)
227
+ if len(body) > limit:
228
+ return None, _too_large()
229
+ try:
230
+ data = json.loads(body)
231
+ except (ValueError, RecursionError):
232
+ return None, _bad_request("Request body must be valid JSON.")
233
+ if not isinstance(data, dict):
234
+ return None, _bad_request("Request body must be a JSON object.")
235
+ return data, None
236
+
237
+
238
+ def _format_graphql_error(error, debug=False):
239
+ """Surface GraphQL and intentional ValueError messages; mask unexpected server exceptions."""
240
+ original = error.original_error
241
+ if original is None or isinstance(original, (GraphQLError, ValueError, SecretBoxError)):
242
+ formatted = format_error(error, debug)
243
+ message = formatted.get("message", "")
244
+ suggestion = message.find(" Did you mean")
245
+ if suggestion != -1:
246
+ # graphql-core embeds schema hints ("Did you mean 'viewer'?") into
247
+ # validation error messages; strip them so errors do not enumerate
248
+ # the schema to probing clients.
249
+ stripped = message[:suggestion].rstrip()
250
+ formatted["message"] = stripped if stripped.endswith(".") else stripped + "."
251
+ extensions = formatted.get("extensions") or {}
252
+ if extensions.get("code") in ("FORBIDDEN", "AUTHENTICATION_ERROR"):
253
+ formatted["extensions"] = {**extensions, "agentHint": DENY_HINT}
254
+ return formatted
255
+ _graphql_log.error("GraphQL resolver failed", exc_info=original)
256
+ return {"message": "Internal error", "extensions": {"code": "INTERNAL_SERVER_ERROR"}}
257
+
258
+
259
+ def _password_matches(stored: str, candidate: str) -> bool:
260
+ return Store._verify_password(candidate, stored)
261
+
262
+
263
+ class _FailureLimiter:
264
+ """Sliding window of failed sign-ins per client IP and email, persisted in rate_limit_event.
265
+
266
+ Shared across workers and restarts because state lives in the database.
267
+ """
268
+
269
+ def __init__(self, engine, bucket: str, limit: int, window_seconds: float):
270
+ self._engine = engine
271
+ self._bucket = bucket
272
+ self._limit = limit
273
+ self._window = window_seconds
274
+
275
+ def blocked(self, keys: list[str]) -> bool:
276
+ return rate_limit_blocked(self._engine, self._bucket, keys, self._limit, self._window)
277
+
278
+ def record(self, keys: list[str]) -> None:
279
+ rate_limit_record(self._engine, self._bucket, keys, self._window)
280
+
281
+
282
+ def _too_many_attempts() -> JSONResponse:
283
+ return JSONResponse(
284
+ {"error": "Too many failed sign-in attempts. Try again later."},
285
+ status_code=429,
286
+ headers={"Retry-After": str(_LOGIN_FAILURE_WINDOW_SECONDS)},
287
+ )
288
+
289
+
290
+ def _with_agent_hint(body: bytes, status: int) -> bytes:
291
+ """Attach the model-facing denial hint to a JSON error body (GraphQL-shaped or plain)."""
292
+ try:
293
+ data = json.loads(body)
294
+ except ValueError:
295
+ return body
296
+ if not isinstance(data, dict):
297
+ return body
298
+ if "errors" in data:
299
+ extensions = data.get("extensions")
300
+ data["extensions"] = {**(extensions if isinstance(extensions, dict) else {}), "agentHint": hint_for(status)}
301
+ else:
302
+ data["agentHint"] = hint_for(status)
303
+ return json.dumps(data).encode()
304
+
305
+
306
+ class _SecurityHeaders:
307
+ """Adds baseline security headers to every HTTP response."""
308
+
309
+ def __init__(self, app):
310
+ self.app = app
311
+
312
+ async def __call__(self, scope, receive, send):
313
+ if scope["type"] != "http":
314
+ await self.app(scope, receive, send)
315
+ return
316
+
317
+ denied_start = None
318
+ denied_body = b""
319
+
320
+ async def send_with_headers(message):
321
+ nonlocal denied_start, denied_body
322
+ if message["type"] == "http.response.start":
323
+ headers = MutableHeaders(scope=message)
324
+ headers["X-Content-Type-Options"] = "nosniff"
325
+ headers["X-Frame-Options"] = "DENY"
326
+ headers["Referrer-Policy"] = "same-origin"
327
+ if headers.get("content-type", "").startswith("text/html"):
328
+ headers["Content-Security-Policy"] = _CSP_HTML
329
+ if message["status"] in (401, 403, 429):
330
+ _security_log.warning("denied status=%s method=%s path=%s",
331
+ message["status"], scope.get("method"), scope.get("path"))
332
+ if headers.get("content-type", "").startswith("application/json"):
333
+ denied_start = message
334
+ return
335
+ elif message["type"] == "http.response.body" and denied_start is not None:
336
+ denied_body += message.get("body", b"")
337
+ if message.get("more_body"):
338
+ return
339
+ denied_body = _with_agent_hint(denied_body, denied_start["status"])
340
+ MutableHeaders(scope=denied_start)["content-length"] = str(len(denied_body))
341
+ await send(denied_start)
342
+ await send({"type": "http.response.body", "body": denied_body})
343
+ return
344
+ await send(message)
345
+
346
+ await self.app(scope, receive, send_with_headers)
347
+
348
+
349
+ def create_app(
350
+ db_path: str | None = None,
351
+ *,
352
+ database_url: str | None = None,
353
+ tenant: str = "default",
354
+ open_mode: bool | None = None,
355
+ trusted_proxy_cidrs: str | None = None,
356
+ trusted_public_host: str | None = None,
357
+ meeting_sfu: object = "env",
358
+ ) -> Starlette:
359
+ target = resolve_database_target(database_url=database_url, db_path=db_path, tenant=tenant)
360
+ engine = make_engine(target)
361
+ store = Store(engine)
362
+ writer = Writer(engine)
363
+ # Set during lifespan when HOJA_AGENT_DBOS_URL enables durable agent turns.
364
+ durable_agent = None
365
+ # Sign-up is configured (or refused) once, at startup. An enabled mode with a
366
+ # missing credential raises here — a clear error beats a silent allow.
367
+ try:
368
+ signup_config = load_signup_config()
369
+ except SignupConfigError as exc:
370
+ raise SignupConfigError(f"Sign-up configuration is invalid: {exc}") from exc
371
+ signup_store = SignupStore(engine)
372
+ signup_gate = SignupGate(config=signup_config, store=signup_store)
373
+ # GraphQL/sync work runs in worker threads. SQLite serializes on the GIL per
374
+ # fetched row, so more than a handful of concurrent readers only adds
375
+ # contention; PostgreSQL drivers release the GIL while waiting on the server.
376
+ default_slots = 8 if engine.dialect.name == "sqlite" else 24
377
+ gql_slots = asyncio.Semaphore(int(os.environ.get("HOJA_GRAPHQL_CONCURRENCY", default_slots)))
378
+ hub = realtime.RealtimeHub(store)
379
+ meeting_service = MeetingService(engine)
380
+ meeting_hub = MeetingHub(meeting_service)
381
+ sfu = CloudflareRealtime.from_env() if meeting_sfu == "env" else meeting_sfu
382
+ issue_snapshots = sync.SingleFlightCache(8)
383
+ body_snapshots = sync.SingleFlightCache(32)
384
+ meta_cache = sync.SingleFlightCache(512)
385
+ issue_lineage: dict = {} # (org, cutoff, visibility) -> (seq, rows) of the newest snapshot
386
+ sync_auth_cache: dict = {}
387
+
388
+ def _validate_creds(creds):
389
+ keys = [h for kind, h in creds if kind == "key"]
390
+ sessions = [h for kind, h in creds if kind == "session"]
391
+ return store.validate_credentials(keys, sessions)
392
+
393
+ hub.validate = _validate_creds
394
+
395
+ if open_mode is None:
396
+ open_mode = os.environ.get("HOJA_SERVER_OPEN", "0") == "1"
397
+
398
+ limiter = _FailureLimiter(engine, "login_failure", _LOGIN_FAILURE_LIMIT, _LOGIN_FAILURE_WINDOW_SECONDS)
399
+
400
+ def _same_origin(origin: str | None, headers) -> bool:
401
+ if origin is None:
402
+ return True
403
+ parts = urlsplit(origin)
404
+ if parts.scheme not in ("http", "https") or not parts.netloc:
405
+ return False
406
+ allowed = {(headers.get("host") or "").strip().lower()}
407
+ if public_host.strip():
408
+ allowed.add(public_host.strip().lower())
409
+ return parts.netloc.lower() in allowed
410
+
411
+ def _cookie_csrf_error(request: Request, *, json_only: bool):
412
+ """Cookie-authenticated writes must come from the same origin (and be JSON for API routes)."""
413
+ if request.method in ("GET", "HEAD", "OPTIONS"):
414
+ return None
415
+ if request.headers.get("authorization") or not request.cookies.get("hoja_session"):
416
+ return None
417
+ if not _same_origin(request.headers.get("origin"), request.headers):
418
+ return JSONResponse(
419
+ {"errors": [{"message": "Cross-site request rejected.", "extensions": {"code": "FORBIDDEN"}}]},
420
+ status_code=403,
421
+ )
422
+ content_type = request.headers.get("content-type", "").split(";")[0].strip().lower()
423
+ if json_only and content_type != "application/json":
424
+ return JSONResponse(
425
+ {"errors": [{"message": "Content-Type must be application/json.", "extensions": {"code": "FORBIDDEN"}}]},
426
+ status_code=403,
427
+ )
428
+ return None
429
+
430
+ def _cookie_secure(request: Request) -> bool:
431
+ if _request_from_trusted_proxy(request):
432
+ # The trusted proxy terminates TLS; the proxy-to-app hop never
433
+ # leaves the host. Do not let a forwarded proto value downgrade
434
+ # the Secure flag on session cookies.
435
+ return True
436
+ if request.url.scheme == "https":
437
+ return True
438
+ return request.url.hostname not in ("localhost", "127.0.0.1", "::1")
439
+
440
+ def _is_loopback(request: Request) -> bool:
441
+ host = request.client.host if request.client else ""
442
+ if host == "localhost":
443
+ return True
444
+ try:
445
+ return ipaddress.ip_address(host).is_loopback
446
+ except ValueError:
447
+ return False
448
+
449
+ def _client_ip(request: Request) -> str:
450
+ peer = request.client.host if request.client else "unknown"
451
+ if _request_from_trusted_proxy(request):
452
+ # Behind Cloudflare the connecting client's real address is carried
453
+ # in CF-Connecting-IP (set by the edge, overriding any client-supplied
454
+ # value). X-Forwarded-For's FIRST entry is the original client; the
455
+ # last entry is only the most recent proxy hop (a shared address).
456
+ client_ip = request.headers.get("cf-connecting-ip", "").strip()
457
+ if client_ip:
458
+ return client_ip
459
+ forwarded = request.headers.get("x-forwarded-for", "").split(",")[0].strip()
460
+ if forwarded:
461
+ return forwarded
462
+ return peer
463
+
464
+ def _limit_keys(request: Request, email: str) -> list[str]:
465
+ keys = [f"ip:{_client_ip(request)}"]
466
+ if email:
467
+ keys.append(f"email:{email}")
468
+ return keys
469
+
470
+ def _open_mode_identity(request: Request):
471
+ if not open_mode or not _is_loopback(request):
472
+ return None, None, None, False
473
+ uid, org = _first_identity(engine)
474
+ if uid:
475
+ request.state.api_key_access = "read_write"
476
+ return uid, org, None, False
477
+ return None, None, None, False
478
+
479
+ def _auth(request: Request):
480
+ """Resolve the caller, then scope the rest of this request to its organization.
481
+
482
+ Credential lookups run before any tenant is known, so they are a system
483
+ operation; everything after a successful resolution is tenant-scoped.
484
+ """
485
+ with tenant_context.system():
486
+ result = _resolve_auth(request)
487
+ if result[0]:
488
+ tenant_context.bind(result[1])
489
+ return result
490
+
491
+ def _resolve_auth(request: Request):
492
+ raw = request.headers.get("authorization", "") or request.headers.get("Authorization", "")
493
+ token = raw[7:].strip() if raw.lower().startswith("bearer ") else raw.strip()
494
+ if raw and token:
495
+ # A valid Authorization header is authoritative; cookies are not consulted.
496
+ key = store.resolve_token(token)
497
+ if key:
498
+ store.touch_api_key(key["id"], key.get("last_used_at"))
499
+ request.state.api_key_access = key["access"]
500
+ return key["user_id"], key["organization_id"], None, False
501
+ # The presented credential did not resolve (e.g. the browser SPA's
502
+ # "session" sentinel). Fall through to the browser session cookie
503
+ # instead of rejecting the request outright.
504
+ session_token = request.cookies.get("hoja_session")
505
+ if session_token:
506
+ session = store.resolve_browser_session(session_token)
507
+ if session:
508
+ member = store.membership_for_profile(
509
+ session["organization_id"], session["user_id"]
510
+ )
511
+ request.state.api_key_access = "read_write"
512
+ return (
513
+ session["user_id"],
514
+ session["organization_id"],
515
+ (member or {}).get("identity_id"),
516
+ True,
517
+ )
518
+ return _open_mode_identity(request)
519
+
520
+ def _socket_identity(websocket):
521
+ """_auth for a realtime socket, plus the credential to revalidate it by."""
522
+ uid, org, _identity_id, _is_session = _auth(websocket)
523
+ if not uid:
524
+ return None, None, None
525
+ raw = websocket.headers.get("authorization", "")
526
+ token = raw[7:].strip() if raw.lower().startswith("bearer ") else raw.strip()
527
+ if token and store.resolve_token(token):
528
+ return uid, org, ("key", token_hash(token))
529
+ session_token = websocket.cookies.get("hoja_session")
530
+ if session_token and _is_session:
531
+ return uid, org, ("session", token_hash(session_token))
532
+ return uid, org, None # loopback open mode: nothing to revoke
533
+
534
+ def _auth_sync(request: Request):
535
+ """_auth for the read-only /sync endpoints, cached briefly per credential."""
536
+ key = (request.headers.get("authorization") or "", request.cookies.get("hoja_session") or "",
537
+ request.client.host if request.client else "")
538
+ now = time.monotonic()
539
+ hit = sync_auth_cache.get(key)
540
+ if hit is not None and now - hit[0] < _SYNC_AUTH_TTL:
541
+ request.state.api_key_access = hit[2]
542
+ # a cache hit skips _auth, so it must scope the request itself
543
+ tenant_context.bind(hit[1][1])
544
+ return hit[1]
545
+ result = _auth(request)
546
+ if result[0]:
547
+ if len(sync_auth_cache) > 10000:
548
+ sync_auth_cache.clear()
549
+ sync_auth_cache[key] = (now, result, getattr(request.state, "api_key_access", "read_write"))
550
+ return result
551
+
552
+ def _credential_slot(uid: str, org: str):
553
+ """Return (table, key column, key value, stored hash) for the account's password."""
554
+ member = store.membership_for_profile(org, uid)
555
+ with engine.connect() as conn:
556
+ if member and member.get("identity_id"):
557
+ stored = conn.execute(
558
+ select(identity_credential.c.password_hash).where(
559
+ identity_credential.c.identity_id == member["identity_id"])
560
+ ).scalar_one_or_none()
561
+ return identity_credential, identity_credential.c.identity_id, member["identity_id"], stored
562
+ stored = conn.execute(
563
+ select(password_credential.c.password_hash).where(password_credential.c.user_id == uid)
564
+ ).scalar_one_or_none()
565
+ return password_credential, password_credential.c.user_id, uid, stored
566
+
567
+ def _password_on_file(uid: str, org: str) -> bool:
568
+ return _credential_slot(uid, org)[3] is not None
569
+
570
+ def _password_matches_account(uid: str, org: str, candidate: str) -> bool:
571
+ stored = _credential_slot(uid, org)[3]
572
+ return stored is not None and _password_matches(stored, candidate)
573
+
574
+ def _replace_password(uid: str, org: str, password: str) -> None:
575
+ if len(password) < 12:
576
+ raise ValueError("Password must be at least 12 characters.")
577
+ table, key_column, key_value, _stored = _credential_slot(uid, org)
578
+ encoded = Store._password_digest(password, secrets.token_bytes(16))
579
+ revoked_at = now_iso()
580
+ with engine.begin() as conn:
581
+ conn.execute(table.update().where(key_column == key_value).values(
582
+ password_hash=encoded, updated_at=revoked_at))
583
+ # A password change ends every browser session of the identity's profiles.
584
+ member = store.membership_for_profile(org, uid)
585
+ profile_ids = [uid]
586
+ if member and member.get("identity_id"):
587
+ profile_ids = [row[0] for row in conn.execute(
588
+ select(organization_membership.c.profile_user_id).where(
589
+ organization_membership.c.identity_id == member["identity_id"]))] or [uid]
590
+ conn.execute(browser_session.update().where(
591
+ browser_session.c.user_id.in_(profile_ids),
592
+ browser_session.c.revoked_at.is_(None)).values(revoked_at=revoked_at))
593
+
594
+ def _email_password_ok(email: str, password: str) -> bool:
595
+ for row in store.workspaces_for_email(email):
596
+ stored = _credential_slot(row["profile_user_id"], row["organization_id"])[3]
597
+ if stored is not None and _password_matches(stored, password):
598
+ return True
599
+ return False
600
+
601
+ def _mcp_oauth_auth(request: Request):
602
+ """Resolve a valid MCP access token to the same pinned Hoja identity."""
603
+ raw = request.headers.get("authorization", "")
604
+ if not raw.lower().startswith("bearer "):
605
+ return None
606
+ from datetime import datetime, timezone
607
+
608
+ from sqlalchemy import select
609
+
610
+ from hoja_server.db import oauth_access_token
611
+
612
+ digest = token_hash(raw[7:].strip())
613
+ with engine.connect() as conn:
614
+ row = (
615
+ conn.execute(
616
+ select(oauth_access_token).where(
617
+ oauth_access_token.c.token_hash == digest,
618
+ oauth_access_token.c.revoked_at.is_(None),
619
+ oauth_access_token.c.expires_at > datetime.now(timezone.utc).isoformat(),
620
+ )
621
+ )
622
+ .mappings()
623
+ .first()
624
+ )
625
+ if not row:
626
+ return None
627
+ member = store.membership_for_profile(row["organization_id"], row["user_id"])
628
+ if not member:
629
+ return None
630
+ return {
631
+ "user_id": row["user_id"],
632
+ "org_id": row["organization_id"],
633
+ "identity_id": member.get("identity_id"),
634
+ "scopes": row["scopes"],
635
+ "client_id": row["client_id"],
636
+ "org_name": (store.workspace(row["organization_id"]) or {}).get("name"),
637
+ }
638
+
639
+ from hoja_server.mcp_oauth import HojaOAuthProvider, build_server
640
+
641
+ # OAuth stays fully disabled unless an explicit public origin and trusted
642
+ # proxy CIDR configuration are provided by the deployment.
643
+ proxy_cidrs = (
644
+ os.environ.get("HOJA_TRUSTED_PROXY_CIDRS", "")
645
+ if trusted_proxy_cidrs is None
646
+ else trusted_proxy_cidrs
647
+ )
648
+ public_host = (
649
+ os.environ.get("HOJA_TRUSTED_PUBLIC_HOST", "")
650
+ if trusted_public_host is None
651
+ else trusted_public_host
652
+ )
653
+ proxy_networks = []
654
+ if proxy_cidrs.strip() and public_host.strip():
655
+ try:
656
+ proxy_networks = [
657
+ ipaddress.ip_network(item.strip(), strict=False)
658
+ for item in proxy_cidrs.split(",")
659
+ if item.strip()
660
+ ]
661
+ except ValueError as exc:
662
+ raise ValueError("HOJA_TRUSTED_PROXY_CIDRS must be comma-separated IP networks.") from exc
663
+ trust_proxy = bool(proxy_networks) and _valid_public_host(public_host)
664
+
665
+ def _request_from_trusted_proxy(request: Request) -> bool:
666
+ if not trust_proxy:
667
+ return False
668
+ peer = request.client.host if request.client else None
669
+ try:
670
+ address = ipaddress.ip_address(peer) if peer else None
671
+ except ValueError:
672
+ return False
673
+ return bool(address and any(address in network for network in proxy_networks))
674
+ mcp_provider = HojaOAuthProvider(engine, store, trusted_proxy=trust_proxy)
675
+ mcp_server = build_server(mcp_provider, public_host=public_host)
676
+ # SDK auth and protected-resource routes are root-relative to its Starlette
677
+ # app; Mount strips /mcp while preserving it in root_path for metadata URLs.
678
+ from mcp.server.transport_security import TransportSecuritySettings
679
+
680
+ mcp_asgi = mcp_server.streamable_http_app(
681
+ streamable_http_path="/", stateless_http=True,
682
+ transport_security=TransportSecuritySettings(
683
+ enable_dns_rebinding_protection=True,
684
+ allowed_hosts=[public_host.strip(), public_host.strip() + ":*"],
685
+ ),
686
+ )
687
+
688
+ async def mcp_endpoint(scope, receive, send):
689
+ request = Request(scope)
690
+ auth_context = _mcp_oauth_auth(request)
691
+ trusted_peer = _request_from_trusted_proxy(request)
692
+ incoming_host = request.headers.get("host", "").lower()
693
+ canonical_host = public_host.strip().lower()
694
+ host_ok = incoming_host == canonical_host or incoming_host.startswith(canonical_host + ":")
695
+ if trust_proxy and (not trusted_peer or not host_ok):
696
+ auth_context = None
697
+ if not host_ok:
698
+ response = JSONResponse({"error": "Untrusted Host header."}, status_code=421)
699
+ await response(scope, receive, send)
700
+ return
701
+ response = JSONResponse({"error": "Request did not originate from a trusted proxy."}, status_code=403)
702
+ await response(scope, receive, send)
703
+ return
704
+ # The browser authorize/consent endpoints authenticate via the existing
705
+ # Hoja session cookie; only MCP resource calls use the OAuth bearer.
706
+ if scope.get("method") in ("GET", "POST") and scope.get("path", "").endswith("/oauth/consent"):
707
+ uid, org, identity_id, is_session = _auth(request)
708
+ if uid and is_session:
709
+ member = store.membership_for_profile(org, uid)
710
+ auth_context = {
711
+ "user_id": uid,
712
+ "org_id": org,
713
+ "identity_id": identity_id or (member or {}).get("identity_id"),
714
+ "org_name": (store.workspace(org) or {}).get("name"),
715
+ "source": "browser_session",
716
+ }
717
+ scope["hoja_auth"] = auth_context
718
+ root_path = scope.get("root_path", "")
719
+ if root_path.endswith("/.well-known/oauth-authorization-server/mcp"):
720
+ scope["path"] = "/.well-known/oauth-authorization-server"
721
+ scope["root_path"] = ""
722
+ elif root_path.endswith("/.well-known/oauth-protected-resource/mcp"):
723
+ scope["path"] = "/.well-known/oauth-protected-resource/mcp"
724
+ scope["root_path"] = ""
725
+ await mcp_asgi(scope, receive, send)
726
+
727
+ async def authorization_metadata_endpoint(request: Request):
728
+ if not trust_proxy:
729
+ return JSONResponse({"error": "OAuth is not configured."}, status_code=404)
730
+ if not _request_from_trusted_proxy(request):
731
+ return JSONResponse({"error": "OAuth is available only behind the configured trusted proxy."}, status_code=404)
732
+ origin = f"https://{public_host}" if trust_proxy else "https://mcp.invalid"
733
+ issuer = origin + "/mcp"
734
+ return JSONResponse({"issuer": issuer, "authorization_endpoint": issuer + "/authorize", "token_endpoint": issuer + "/token", "registration_endpoint": issuer + "/register", "revocation_endpoint": issuer + "/revoke", "scopes_supported": ["hoja:read", "hoja:write"], "response_types_supported": ["code"], "grant_types_supported": ["authorization_code", "refresh_token"], "code_challenge_methods_supported": ["S256"]})
735
+
736
+ async def resource_metadata_endpoint(request: Request):
737
+ if not trust_proxy:
738
+ return JSONResponse({"error": "OAuth is not configured."}, status_code=404)
739
+ if not _request_from_trusted_proxy(request):
740
+ return JSONResponse({"error": "OAuth is available only behind the configured trusted proxy."}, status_code=404)
741
+ issuer = (f"https://{public_host}" if trust_proxy else "https://mcp.invalid") + "/mcp"
742
+ return JSONResponse({"resource": issuer, "authorization_servers": [issuer], "scopes_supported": ["hoja:read"]})
743
+
744
+ from starlette.routing import Mount
745
+
746
+ async def realtime_socket(websocket: WebSocket):
747
+ from starlette.datastructures import Headers
748
+
749
+ raw_headers = Headers(scope=websocket.scope)
750
+ if not _same_origin(raw_headers.get("origin"), raw_headers):
751
+ await websocket.close(code=1008)
752
+ return
753
+ offered = websocket.scope.get("subprotocols") or []
754
+ subprotocol = "bearer" if "bearer" in offered else None
755
+ token_header = ""
756
+ if subprotocol and len(offered) > 1:
757
+ token_header = f"Bearer {offered[1]}"
758
+ websocket.scope["headers"] = [
759
+ *websocket.scope["headers"],
760
+ *([(b"authorization", token_header.encode())] if token_header else []),
761
+ ]
762
+ uid, org, cred = await run_in_threadpool(_socket_identity, websocket)
763
+ if uid: # resolved in a worker thread: its context copy is gone, bind here
764
+ tenant_context.bind(org)
765
+ await websocket.accept(subprotocol=subprotocol)
766
+ if not uid:
767
+ await websocket.close(code=4401)
768
+ return
769
+ raw_after = websocket.query_params.get("after")
770
+ cursor = None
771
+ if raw_after is not None:
772
+ try:
773
+ cursor = int(raw_after)
774
+ except ValueError:
775
+ await websocket.close(code=4400)
776
+ return
777
+ if not 0 <= cursor <= _MAX_SEQ:
778
+ await websocket.close(code=4400)
779
+ return
780
+ proto = 2 if websocket.query_params.get("v") == "2" else 1
781
+ await hub.serve(websocket, uid, org, cred, cursor, proto)
782
+
783
+ async def agent_chat_server(request: Request):
784
+ uid, org, _identity_id, _is_browser = _auth(request)
785
+ if not uid:
786
+ return JSONResponse(
787
+ {"errors": [{"message": "Authentication required", "extensions": {"code": "AUTHENTICATION_ERROR"}}]},
788
+ status_code=401,
789
+ )
790
+ csrf = _cookie_csrf_error(request, json_only=True)
791
+ if csrf:
792
+ return csrf
793
+ body = await request.json()
794
+ messages = body.get("messages") if isinstance(body, dict) else None
795
+ if not isinstance(messages, list) or not messages:
796
+ return JSONResponse({"error": "messages is required"}, status_code=400)
797
+ from hoja_server.agent_chat import sse_response, stream_reply
798
+ from hoja_server.schema_sdl import SCHEMA_SDL
799
+ base_context = {
800
+ "request": request,
801
+ "store": store,
802
+ "writer": writer,
803
+ "org_id": org,
804
+ "user_id": uid,
805
+ "identity_id": _identity_id,
806
+ "browser_session": _is_browser,
807
+ "access": getattr(request.state, "api_key_access", "read_write"),
808
+ }
809
+ try:
810
+ thread_id = body.get("threadId") if isinstance(body, dict) else None
811
+ connector = connector_binding_for(engine, org, uid)
812
+ if durable_agent is not None:
813
+ gen = durable_agent.stream_reply(store, org, uid, messages, base_context, thread_id, connector)
814
+ else:
815
+ gen = stream_reply(store, org, uid, messages, _schema, SCHEMA_SDL, base_context, thread_id, connector)
816
+ first = await gen.__anext__()
817
+ except ValueError as exc:
818
+ return JSONResponse({"error": str(exc)}, status_code=400)
819
+
820
+ async def _resume():
821
+ yield first
822
+ async for chunk in gen:
823
+ yield chunk
824
+
825
+ return sse_response(_resume())
826
+
827
+ async def _agent_auth(request: Request):
828
+ uid, org, _identity_id, _is_browser = _auth(request)
829
+ if not uid:
830
+ return None, None, JSONResponse(
831
+ {"errors": [{"message": "Authentication required", "extensions": {"code": "AUTHENTICATION_ERROR"}}]},
832
+ status_code=401,
833
+ )
834
+ if request.method != "GET" and getattr(request.state, "api_key_access", "read_write") == "read":
835
+ return None, None, JSONResponse(
836
+ {"errors": [{"message": "This API key is read-only.", "extensions": {"code": "FORBIDDEN"}}]},
837
+ status_code=403,
838
+ )
839
+ csrf = _cookie_csrf_error(request, json_only=True)
840
+ if csrf:
841
+ return None, None, csrf
842
+ return uid, org, None
843
+
844
+ async def agent_threads_list(request: Request):
845
+ from hoja_server import agent_threads
846
+ uid, org, err = await _agent_auth(request)
847
+ if err:
848
+ return err
849
+ return JSONResponse(agent_threads.list_threads(store, org, uid))
850
+
851
+ async def agent_threads_create(request: Request):
852
+ from hoja_server import agent_threads
853
+ uid, org, err = await _agent_auth(request)
854
+ if err:
855
+ return err
856
+ body = await request.json()
857
+ messages = body.get("messages") if isinstance(body, dict) else None
858
+ if not isinstance(messages, list):
859
+ return JSONResponse({"error": "messages is required"}, status_code=400)
860
+ return JSONResponse(agent_threads.create_thread(store, org, uid, messages))
861
+
862
+ async def agent_thread_get(request: Request):
863
+ from hoja_server import agent_threads
864
+ uid, org, err = await _agent_auth(request)
865
+ if err:
866
+ return err
867
+ messages = agent_threads.get_messages(store, org, uid, request.path_params["thread_id"])
868
+ if messages is None:
869
+ return JSONResponse({"error": "Thread not found"}, status_code=404)
870
+ return JSONResponse(messages)
871
+
872
+ async def agent_thread_update(request: Request):
873
+ from hoja_server import agent_threads
874
+ uid, org, err = await _agent_auth(request)
875
+ if err:
876
+ return err
877
+ body = await request.json()
878
+ title = body.get("title") if isinstance(body, dict) else None
879
+ thread = agent_threads.update_thread(store, org, uid, request.path_params["thread_id"], title if isinstance(title, str) else None)
880
+ if thread is None:
881
+ return JSONResponse({"error": "Thread not found"}, status_code=404)
882
+ return JSONResponse(thread)
883
+
884
+ async def agent_thread_delete(request: Request):
885
+ from hoja_server import agent_threads
886
+ uid, org, err = await _agent_auth(request)
887
+ if err:
888
+ return err
889
+ if not agent_threads.delete_thread(store, org, uid, request.path_params["thread_id"]):
890
+ return JSONResponse({"error": "Thread not found"}, status_code=404)
891
+ return JSONResponse({"success": True})
892
+
893
+ async def graphql_server(request: Request):
894
+ uid, org, identity_id, is_browser_session = await run_in_threadpool(_auth, request)
895
+ if uid: # resolved in a worker thread: its context copy is gone, bind here
896
+ tenant_context.bind(org)
897
+ if not uid:
898
+ return JSONResponse(
899
+ {
900
+ "errors": [
901
+ {
902
+ "message": "Authentication required",
903
+ "extensions": {"code": "AUTHENTICATION_ERROR"},
904
+ }
905
+ ]
906
+ },
907
+ status_code=401,
908
+ )
909
+ csrf = _cookie_csrf_error(request, json_only=True)
910
+ if csrf:
911
+ return csrf
912
+ data, error = await _read_json_object(request, _MAX_GRAPHQL_BODY)
913
+ if error:
914
+ return error
915
+ query = data.get("query")
916
+ variables = data.get("variables")
917
+ if query is not None and not isinstance(query, str):
918
+ return _bad_request("query must be a string.")
919
+ if variables is not None and not isinstance(variables, dict):
920
+ return _bad_request("variables must be an object.")
921
+ access = getattr(request.state, "api_key_access", "read_write")
922
+ if isinstance(query, str):
923
+ problem = _query_problem(query)
924
+ if problem:
925
+ return _bad_request(problem)
926
+ from hoja_server.agent_chat import read_only_violation
927
+
928
+ if read_only_violation(query, access):
929
+ return JSONResponse(
930
+ {"errors": [{"message": "This API key is read-only.",
931
+ "extensions": {"code": "FORBIDDEN"}}]},
932
+ status_code=403,
933
+ )
934
+ context = {
935
+ "request": request,
936
+ "store": store,
937
+ "cache": {},
938
+ "writer": writer,
939
+ "org_id": org,
940
+ "user_id": uid,
941
+ "identity_id": identity_id,
942
+ "browser_session": is_browser_session,
943
+ "access": access,
944
+ }
945
+ # Sync resolvers would otherwise run on the event loop and block every
946
+ # WS client; execute the whole GraphQL operation in a worker thread.
947
+ async with gql_slots:
948
+ _success, result = await run_in_threadpool(
949
+ graphql_sync,
950
+ _schema,
951
+ data,
952
+ context_value=context,
953
+ error_formatter=_format_graphql_error,
954
+ debug=(os.environ.get("HOJA_SERVER_DEBUG", "0") == "1"),
955
+ )
956
+ if isinstance(query, str) and "mutation" in query:
957
+ hub.kick()
958
+ target = context.get("switch_target")
959
+ if target:
960
+ session_token, _details = store.create_session_for_membership(
961
+ target.get("identity_id", identity_id), target["user_id"], target["organization_id"]
962
+ )
963
+ if not session_token:
964
+ return JSONResponse(
965
+ {"errors": [{"message": "Workspace access revoked"}]}, status_code=403
966
+ )
967
+ raw = request.cookies.get("hoja_session")
968
+ if raw:
969
+ store.revoke_browser_session(raw)
970
+ response = JSONResponse(result, status_code=200)
971
+ response.set_cookie(
972
+ "hoja_session",
973
+ session_token,
974
+ httponly=True,
975
+ secure=_cookie_secure(request),
976
+ samesite="lax",
977
+ max_age=14 * 24 * 60 * 60,
978
+ path="/",
979
+ )
980
+ return response
981
+ return JSONResponse(result, status_code=200)
982
+
983
+ async def auth_setup(request: Request):
984
+ if request.method == "GET":
985
+ return JSONResponse(
986
+ {"setup": True, "message": "Set a password using a valid local API token."}
987
+ )
988
+ csrf = _cookie_csrf_error(request, json_only=False)
989
+ if csrf:
990
+ return csrf
991
+ body = await request.json()
992
+ password = str(body.get("password", ""))
993
+ setup_token = str(body.get("token", ""))
994
+ setup_email = str(body.get("email", "")).strip().lower()
995
+ session_token = request.cookies.get("hoja_session")
996
+ session = store.resolve_browser_session(session_token) if session_token else None
997
+ try:
998
+ if session and _password_on_file(session["user_id"], session["organization_id"]):
999
+ if not _password_matches_account(
1000
+ session["user_id"], session["organization_id"], str(body.get("currentPassword", ""))
1001
+ ):
1002
+ return JSONResponse({"error": "Current password is incorrect."}, status_code=401)
1003
+ _replace_password(session["user_id"], session["organization_id"], password)
1004
+ return JSONResponse({"status": "password_set"}, status_code=201)
1005
+ identity = store.resolve_token(setup_token)
1006
+ if identity and _password_on_file(identity["user_id"], identity["organization_id"]):
1007
+ return JSONResponse(
1008
+ {"error": "A password is already set. Sign in and change it with your current password."},
1009
+ status_code=403,
1010
+ )
1011
+ if identity and identity["access"] == "read":
1012
+ return JSONResponse(
1013
+ {"error": "Read-only API keys cannot set a password."}, status_code=403
1014
+ )
1015
+ if setup_email and identity:
1016
+ with engine.connect() as conn:
1017
+ account_email = conn.execute(
1018
+ select(user.c.email).where(user.c.id == identity["user_id"])
1019
+ ).scalar_one_or_none()
1020
+ if not account_email or account_email.strip().lower() != setup_email:
1021
+ return JSONResponse(
1022
+ {"error": "This invite does not match that email address."}, status_code=401
1023
+ )
1024
+ ok = store.set_password(setup_token, password)
1025
+ except ValueError as exc:
1026
+ return JSONResponse({"error": str(exc)}, status_code=400)
1027
+ if not ok:
1028
+ return JSONResponse({"error": "Invalid API token"}, status_code=401)
1029
+ return JSONResponse({"status": "password_set"}, status_code=201)
1030
+
1031
+ async def auth_invite_accept(request: Request):
1032
+ body = await request.json()
1033
+ try:
1034
+ result = store.accept_new_member_invitation(
1035
+ str(body.get("code", "")), str(body.get("email", "")), str(body.get("password", ""))
1036
+ )
1037
+ except ValueError as exc:
1038
+ return JSONResponse({"error": str(exc)}, status_code=400)
1039
+ if not result:
1040
+ return JSONResponse(
1041
+ {"error": "Invite code is invalid, expired, or does not match that email."},
1042
+ status_code=401,
1043
+ )
1044
+ session_token, _identity = result
1045
+ response = JSONResponse({"status": "accepted"})
1046
+ response.set_cookie(
1047
+ "hoja_session",
1048
+ session_token,
1049
+ httponly=True,
1050
+ secure=_cookie_secure(request),
1051
+ samesite="lax",
1052
+ max_age=14 * 24 * 60 * 60,
1053
+ path="/",
1054
+ )
1055
+ return response
1056
+
1057
+ async def onboarding_status(_request: Request):
1058
+ try:
1059
+ initialized = store.is_initialized()
1060
+ except Exception:
1061
+ return JSONResponse({"error": "Setup status unavailable"}, status_code=503)
1062
+ return JSONResponse({"initialized": initialized, "singleOrg": single_org_mode()})
1063
+
1064
+ async def onboarding_bootstrap(request: Request):
1065
+ body = await request.json()
1066
+ name = str(body.get("name", "")).strip()
1067
+ email = str(body.get("email", "")).strip().lower()
1068
+ password = str(body.get("password", ""))
1069
+ workspace_name = str(body.get("workspaceName", "")).strip()
1070
+ workspace_key = str(body.get("workspaceKey", "")).strip().lower()
1071
+ team_name = str(body.get("teamName", "")).strip()
1072
+ team_key = str(body.get("teamKey", "")).strip().upper()
1073
+ if not all((name, workspace_name, workspace_key, team_name, team_key)) or "@" not in email:
1074
+ return JSONResponse(
1075
+ {"error": "Complete all fields with a valid email."}, status_code=400
1076
+ )
1077
+ # A hosted tenant is provisioned with an owner address before it has a
1078
+ # user. The onboarding form must not let another address claim it first.
1079
+ owner = google_login.owner_email()
1080
+ if owner and email != owner:
1081
+ return JSONResponse(
1082
+ {"error": "This workspace is reserved for its owner."}, status_code=403
1083
+ )
1084
+ if len(password) < 12:
1085
+ return JSONResponse(
1086
+ {"error": "Password must be at least 12 characters."}, status_code=400
1087
+ )
1088
+ if not workspace_key.replace("-", "").isalnum() or not team_key.isalnum():
1089
+ return JSONResponse(
1090
+ {
1091
+ "error": "Workspace and team keys may contain only letters, numbers, and workspace hyphens."
1092
+ },
1093
+ status_code=400,
1094
+ )
1095
+
1096
+ raw_api_key = gen_token()
1097
+ session_token = gen_session_token()
1098
+ now = now_iso()
1099
+ identity_id, org_id, uid, tid = new_id(), new_id(), new_id(), new_id()
1100
+ password_hash = Store._password_digest(password, secrets.token_bytes(16))
1101
+ try:
1102
+ # Serialize fresh-instance check and all initial rows in one transaction.
1103
+ with engine.begin() as conn:
1104
+ if conn.dialect.name == "postgresql":
1105
+ conn.execute(text("SELECT pg_advisory_xact_lock(721946031)"))
1106
+ elif conn.dialect.name == "sqlite":
1107
+ conn.exec_driver_sql("BEGIN IMMEDIATE")
1108
+ if conn.execute(select(organization.c.id).limit(1)).first():
1109
+ return JSONResponse(
1110
+ {"error": "This Hoja instance is already set up."}, status_code=409
1111
+ )
1112
+ conn.execute(
1113
+ organization.insert().values(
1114
+ id=org_id,
1115
+ name=workspace_name,
1116
+ url_key=workspace_key,
1117
+ created_at=now,
1118
+ updated_at=now,
1119
+ )
1120
+ )
1121
+ conn.execute(
1122
+ user.insert().values(
1123
+ id=uid,
1124
+ organization_id=org_id,
1125
+ name=name,
1126
+ display_name=name,
1127
+ email=email,
1128
+ active=True,
1129
+ admin=True,
1130
+ timezone="UTC",
1131
+ created_at=now,
1132
+ updated_at=now,
1133
+ )
1134
+ )
1135
+ conn.execute(
1136
+ global_identity.insert().values(id=identity_id, email=email, created_at=now)
1137
+ )
1138
+ conn.execute(
1139
+ organization_membership.insert().values(
1140
+ id=new_id(),
1141
+ identity_id=identity_id,
1142
+ organization_id=org_id,
1143
+ profile_user_id=uid,
1144
+ active=True,
1145
+ created_at=now,
1146
+ )
1147
+ )
1148
+ conn.execute(
1149
+ identity_credential.insert().values(
1150
+ identity_id=identity_id,
1151
+ password_hash=password_hash,
1152
+ created_at=now,
1153
+ updated_at=now,
1154
+ )
1155
+ )
1156
+ conn.execute(
1157
+ api_key.insert().values(
1158
+ id=new_id(),
1159
+ token_hash=token_hash(raw_api_key),
1160
+ label="initial admin",
1161
+ user_id=uid,
1162
+ organization_id=org_id,
1163
+ created_at=now,
1164
+ )
1165
+ )
1166
+ conn.execute(
1167
+ team.insert().values(
1168
+ id=tid,
1169
+ organization_id=org_id,
1170
+ key=team_key,
1171
+ name=team_name,
1172
+ description=f"{team_name} team",
1173
+ color="#5e6ad2",
1174
+ visibility="public",
1175
+ timezone="UTC",
1176
+ issue_counter=0,
1177
+ created_at=now,
1178
+ updated_at=now,
1179
+ )
1180
+ )
1181
+ conn.execute(team_member.insert().values(team_id=tid, user_id=uid, role="owner"))
1182
+ default_state = seed_states_for_team(conn, org_id, tid)
1183
+ conn.execute(
1184
+ team.update().where(team.c.id == tid).values(default_state_id=default_state)
1185
+ )
1186
+ _seed_demo_issues(conn, org_id, tid, team_key, uid, default_state, workspace_key)
1187
+ conn.execute(
1188
+ browser_session.insert().values(
1189
+ id=new_id(),
1190
+ token_hash=token_hash(session_token),
1191
+ user_id=uid,
1192
+ organization_id=org_id,
1193
+ created_at=now,
1194
+ expires_at=(datetime.now(timezone.utc) + timedelta(days=14)).isoformat(),
1195
+ )
1196
+ )
1197
+ except Exception as exc:
1198
+ from sqlalchemy.exc import IntegrityError
1199
+
1200
+ if isinstance(exc, IntegrityError):
1201
+ return JSONResponse(
1202
+ {"error": "Workspace key or email is already in use."}, status_code=409
1203
+ )
1204
+ raise
1205
+ response = JSONResponse(
1206
+ {
1207
+ "status": "created",
1208
+ "apiKey": raw_api_key,
1209
+ "teamId": tid,
1210
+ "workspace": {"id": org_id, "name": workspace_name, "urlKey": workspace_key},
1211
+ }
1212
+ )
1213
+ response.set_cookie(
1214
+ "hoja_session",
1215
+ session_token,
1216
+ httponly=True,
1217
+ secure=_cookie_secure(request),
1218
+ samesite="lax",
1219
+ max_age=14 * 24 * 60 * 60,
1220
+ path="/",
1221
+ )
1222
+ return response
1223
+
1224
+ async def auth_login(request: Request):
1225
+ body = await request.json()
1226
+ keys = _limit_keys(request, str(body.get("email", "")).strip().lower())
1227
+ if limiter.blocked(keys):
1228
+ return _too_many_attempts()
1229
+ response = await _login(request)
1230
+ if response.status_code == 401:
1231
+ limiter.record(keys)
1232
+ return response
1233
+
1234
+ async def _login(request: Request):
1235
+ body = await request.json()
1236
+ email = str(body.get("email", ""))
1237
+ password = str(body.get("password", ""))
1238
+ organization_ref = body.get("organizationId")
1239
+ api_key_value = str(body.get("apiKey", ""))
1240
+ if not api_key_value and not organization_ref:
1241
+ try:
1242
+ matches = store.matching_login_workspaces(email)
1243
+ except Exception as exc:
1244
+ # Old databases may not have the identity/membership schema yet.
1245
+ # Do not disguise unrelated database errors as invalid credentials.
1246
+ from sqlalchemy.exc import OperationalError
1247
+
1248
+ if not isinstance(exc, OperationalError) or "organization_membership" not in str(
1249
+ exc
1250
+ ):
1251
+ raise
1252
+ return JSONResponse(
1253
+ {
1254
+ "error": "Workspace sign-in is unavailable until the database schema is migrated."
1255
+ },
1256
+ status_code=503,
1257
+ )
1258
+ if len(matches) > 1:
1259
+ if not _email_password_ok(email, password):
1260
+ return JSONResponse({"error": "Invalid credentials"}, status_code=401)
1261
+ return JSONResponse(
1262
+ {"error": "Choose a workspace", "workspaces": matches}, status_code=409
1263
+ )
1264
+ if len(matches) == 1:
1265
+ organization_ref = matches[0]["organizationId"]
1266
+ if api_key_value:
1267
+ identity = store.resolve_token(api_key_value)
1268
+ if not identity:
1269
+ return JSONResponse({"error": "Invalid API key"}, status_code=401)
1270
+ if identity["access"] == "read":
1271
+ return JSONResponse(
1272
+ {"error": "Read-only API keys cannot open a browser session."}, status_code=403
1273
+ )
1274
+ # When this identity belongs to several workspaces, an API key is
1275
+ # scoped to only one of them. Honor an explicit workspace selection
1276
+ # rather than silently creating a session in the key's workspace.
1277
+ if organization_ref:
1278
+ member = store.membership_for_profile(
1279
+ identity["organization_id"], identity["user_id"]
1280
+ )
1281
+ selected = store.switch_membership(
1282
+ member.get("identity_id") if member else None, organization_ref
1283
+ )
1284
+ if selected:
1285
+ session_token, _details = store.create_session_for_membership(
1286
+ member["identity_id"], selected["user_id"], selected["organization_id"]
1287
+ )
1288
+ result = (session_token, selected) if session_token else None
1289
+ else:
1290
+ result = None
1291
+ else:
1292
+ result = store.create_browser_session_for_token(api_key_value)
1293
+ else:
1294
+ result = store.create_browser_session(
1295
+ email, password, organization_ref=organization_ref
1296
+ )
1297
+ if not result:
1298
+ return JSONResponse({"error": "Invalid credentials"}, status_code=401)
1299
+ session_token, identity = result
1300
+ response = JSONResponse({"status": "authenticated", "expiresAt": identity["expires_at"]})
1301
+ response.set_cookie(
1302
+ "hoja_session",
1303
+ session_token,
1304
+ httponly=True,
1305
+ secure=_cookie_secure(request),
1306
+ samesite="lax",
1307
+ max_age=14 * 24 * 60 * 60,
1308
+ path="/",
1309
+ )
1310
+ return response
1311
+
1312
+ async def auth_workspaces(request: Request):
1313
+ body = await request.json()
1314
+ email = str(body.get("email", "")).strip().lower()
1315
+ keys = _limit_keys(request, email)
1316
+ if limiter.blocked(keys):
1317
+ return _too_many_attempts()
1318
+ if not _email_password_ok(email, str(body.get("password", ""))):
1319
+ limiter.record(keys)
1320
+ return JSONResponse({"error": "Invalid credentials"}, status_code=401)
1321
+ return JSONResponse({"workspaces": store.matching_login_workspaces(email)})
1322
+
1323
+ async def auth_logout(request: Request):
1324
+ csrf = _cookie_csrf_error(request, json_only=False)
1325
+ if csrf:
1326
+ return csrf
1327
+ session_token = request.cookies.get("hoja_session")
1328
+ if session_token:
1329
+ store.revoke_browser_session(session_token)
1330
+ response = JSONResponse({"status": "logged_out"})
1331
+ response.delete_cookie("hoja_session", path="/")
1332
+ return response
1333
+
1334
+ async def auth_me(request: Request):
1335
+ uid, org, _identity_id, _browser_session = _auth(request)
1336
+ if not uid:
1337
+ return JSONResponse({"error": "Authentication required"}, status_code=401)
1338
+ return JSONResponse({"userId": uid, "organizationId": org})
1339
+
1340
+ # ---- Hosted sign-up: Google-only identity, then the verification gate ----
1341
+ #
1342
+ # The three layers live in their own modules (google_oidc, turnstile,
1343
+ # signup_gate); these handlers only move cookies, calls and JSON. No handler
1344
+ # here creates a database, container, route or DNS record, and none calls a
1345
+ # provisioner: success is one signup_eligibility row for it to pick up.
1346
+ _SIGNUP_SESSION_COOKIE = "hoja_signup_session"
1347
+ _OIDC_FLOW_COOKIE = "hoja_oidc_flow"
1348
+ _SIGNUP_BODY_LIMIT = 8 * 1024
1349
+ #: Where the page starts Google sign-in: same origin, back to the page itself.
1350
+ _GOOGLE_SIGN_IN_URL = "/auth/google/start?return_to=%2Fsignup"
1351
+
1352
+ def _session_cookie_attrs(request: Request) -> dict:
1353
+ """HttpOnly, Secure, SameSite=Lax, Path=/ — the browser_session rule."""
1354
+ return {
1355
+ "httponly": True,
1356
+ "secure": _cookie_secure(request),
1357
+ "samesite": "lax",
1358
+ "path": "/",
1359
+ }
1360
+
1361
+ def _safe_return_to(value: str | None) -> str:
1362
+ """Only a path on this host: an absolute URL here would be an open redirect."""
1363
+ candidate = (value or "").strip()
1364
+ if not candidate.startswith("/") or candidate.startswith("//"):
1365
+ return "/"
1366
+ if "\\" in candidate or any(ch.isspace() for ch in candidate):
1367
+ return "/"
1368
+ parts = urlsplit(candidate)
1369
+ if parts.scheme or parts.netloc:
1370
+ return "/"
1371
+ return candidate
1372
+
1373
+ def _tenant_transfer_target(value: str | None) -> str | None:
1374
+ """A return target on one of OUR tenant hosts, normalised, or None."""
1375
+ return identity_transfer.tenant_target(value)
1376
+
1377
+ def _signup_host(request: Request) -> str:
1378
+ forwarded = (
1379
+ request.headers.get("x-forwarded-host")
1380
+ if _request_from_trusted_proxy(request)
1381
+ else None
1382
+ )
1383
+ return (forwarded or request.headers.get("host") or "").split(",")[0].strip()
1384
+
1385
+ def _signup_identity(request: Request):
1386
+ """The google_verified person behind the sign-up cookie, or None."""
1387
+ return signup_store.resolve_session(request.cookies.get(_SIGNUP_SESSION_COOKIE))
1388
+
1389
+ async def signup_public_config(request: Request):
1390
+ """Everything the sign-up page needs, and nothing it must not have.
1391
+
1392
+ Public by contract: the Turnstile *site* key, which mode is on, and where
1393
+ Google sign-in starts. The site key is public by design (it ships in the
1394
+ page bundle); the siteverify secret, the OIDC client secret, the client id
1395
+ and the expected hostname are never in this response, and the test asserts
1396
+ that the body contains no secret and no unexpected field.
1397
+
1398
+ ``available`` is the fail-closed flag: with no site key the page renders
1399
+ "sign-up unavailable" instead of a widget that could never be verified.
1400
+ ``no-store`` because a stale mode or a stale key is a trap after a deploy.
1401
+ """
1402
+ host = _signup_host(request).split(":")[0].lower()
1403
+ control_plane = signup_config.control_plane_url
1404
+ tenant_origin = bool(
1405
+ control_plane and host != (urlsplit(control_plane).hostname or "").lower()
1406
+ )
1407
+ if tenant_origin:
1408
+ # A tenant borrows the control plane's registered Google redirect.
1409
+ # Returning to `/` means the verified handoff lands in the app, not
1410
+ # on the tenant's closed sign-up page.
1411
+ sign_in_url = "/auth/google/start?return_to=%2F"
1412
+ elif signup_config.configured:
1413
+ sign_in_url = _GOOGLE_SIGN_IN_URL
1414
+ else:
1415
+ sign_in_url = None
1416
+ return JSONResponse(
1417
+ {
1418
+ "mode": signup_config.mode,
1419
+ "available": signup_config.public_widget_available,
1420
+ "sitekey": signup_config.turnstile_site_key or None,
1421
+ "signInUrl": sign_in_url,
1422
+ "hosted": bool(control_plane),
1423
+ "widgetScriptUrl": TURNSTILE_SCRIPT_URL,
1424
+ },
1425
+ headers={"cache-control": "no-store"},
1426
+ )
1427
+
1428
+ def _tenant_transfer_redirect(
1429
+ *,
1430
+ email: str,
1431
+ subject: str,
1432
+ name: str | None,
1433
+ picture: str | None,
1434
+ tenant_target: str,
1435
+ source: str,
1436
+ ) -> Response:
1437
+ """Mint the per-tenant handoff from an already verified identity."""
1438
+ master = signup_config.identity_transfer_master
1439
+ if not master:
1440
+ return JSONResponse(
1441
+ {"error": "Identity handoff is not configured on this deployment.",
1442
+ "reason": "transfer_unconfigured"},
1443
+ status_code=503,
1444
+ )
1445
+ target_host = urlsplit(tenant_target).hostname or ""
1446
+ transfer = identity_transfer.issue(
1447
+ key=identity_transfer.tenant_key(master, target_host),
1448
+ audience=target_host,
1449
+ email=email.strip().lower(),
1450
+ subject=subject,
1451
+ name=name,
1452
+ picture=picture,
1453
+ email_verified=True,
1454
+ )
1455
+ _security_log.info(
1456
+ "auth.handoff source=%s target_host=%s", source, target_host
1457
+ )
1458
+ response = RedirectResponse(
1459
+ f"{tenant_target.rstrip('/')}/auth/google/finish?t={quote(transfer, safe='')}",
1460
+ status_code=302,
1461
+ )
1462
+ response.delete_cookie(_OIDC_FLOW_COOKIE, path="/")
1463
+ return response
1464
+
1465
+ async def google_sign_in_start(request: Request):
1466
+ host = _signup_host(request).split(":")[0].lower()
1467
+ control_plane = signup_config.control_plane_url
1468
+ raw_return_to = request.query_params.get("return_to")
1469
+ tenant_target = _tenant_transfer_target(raw_return_to)
1470
+ identity = _signup_identity(request)
1471
+ _security_log.info(
1472
+ "auth.start host=%s control_session=%s tenant_target=%s",
1473
+ host,
1474
+ bool(identity),
1475
+ urlsplit(tenant_target).hostname if tenant_target else "-",
1476
+ )
1477
+ if control_plane and host != urlsplit(control_plane).hostname:
1478
+ # A tenant origin has no registered Google redirect of its own, so it
1479
+ # borrows the control plane's and comes back to /auth/google/finish.
1480
+ back = _tenant_transfer_target(f"https://{host}/") or f"https://{host}/"
1481
+ target = f"{control_plane}/auth/google/start?return_to={quote(back, safe='')}"
1482
+ return RedirectResponse(target, status_code=302)
1483
+ if identity is not None and tenant_target is not None:
1484
+ # The browser already completed Google OIDC on this control plane.
1485
+ # Do not send it through the account chooser again: the tenant only
1486
+ # needs a freshly minted, audience-bound handoff token.
1487
+ full_identity = signup_store.identity_by_subject(identity["subject"]) or identity
1488
+ if full_identity.get("email_verified") is True:
1489
+ return _tenant_transfer_redirect(
1490
+ email=full_identity["email"],
1491
+ subject=full_identity["subject"],
1492
+ name=full_identity.get("name"),
1493
+ picture=full_identity.get("picture"),
1494
+ tenant_target=tenant_target,
1495
+ source="control_session",
1496
+ )
1497
+ if not signup_config.configured:
1498
+ return JSONResponse(
1499
+ {"error": "Sign-up is not configured on this deployment.",
1500
+ "reason": "signup_unconfigured"},
1501
+ status_code=503,
1502
+ )
1503
+ redirect_uri = signup_config.redirect_uri_for(_signup_host(request))
1504
+ if redirect_uri is None:
1505
+ return JSONResponse(
1506
+ {"error": "This host is not on the redirect allow-list.",
1507
+ "reason": "redirect_uri_not_allowed"},
1508
+ status_code=400,
1509
+ )
1510
+ state = google_oidc.new_secret()
1511
+ nonce = google_oidc.new_secret()
1512
+ binding = google_oidc.new_secret()
1513
+ verifier, challenge = google_oidc.pkce_pair()
1514
+ signup_store.start_flow(
1515
+ state=state,
1516
+ binding=binding,
1517
+ nonce=nonce,
1518
+ code_verifier=verifier,
1519
+ redirect_uri=redirect_uri,
1520
+ return_to=(_tenant_transfer_target(request.query_params.get("return_to"))
1521
+ or _safe_return_to(request.query_params.get("return_to"))),
1522
+ ttl_seconds=signup_config.flow_ttl_seconds,
1523
+ )
1524
+ location = google_oidc.authorization_url(
1525
+ client_id=signup_config.google_client_id,
1526
+ redirect_uri=redirect_uri,
1527
+ state=state,
1528
+ nonce=nonce,
1529
+ code_challenge=challenge,
1530
+ hosted_domain=signup_config.google_hd,
1531
+ )
1532
+ response = RedirectResponse(location, status_code=302)
1533
+ response.set_cookie(
1534
+ _OIDC_FLOW_COOKIE,
1535
+ binding,
1536
+ max_age=signup_config.flow_ttl_seconds,
1537
+ **_session_cookie_attrs(request),
1538
+ )
1539
+ return response
1540
+
1541
+ async def google_sign_in_callback(request: Request):
1542
+ if not signup_config.configured:
1543
+ return JSONResponse(
1544
+ {"error": "Sign-up is not configured on this deployment.",
1545
+ "reason": "signup_unconfigured"},
1546
+ status_code=503,
1547
+ )
1548
+ flow, flow_reason = signup_store.consume_flow(
1549
+ state=request.query_params.get("state") or "",
1550
+ binding=request.cookies.get(_OIDC_FLOW_COOKIE),
1551
+ )
1552
+ if flow is None:
1553
+ # Generic message: a caller learns that it failed, not which check.
1554
+ return JSONResponse(
1555
+ {"error": "This sign-in attempt is invalid or has expired.",
1556
+ "reason": flow_reason},
1557
+ status_code=400,
1558
+ )
1559
+ if request.query_params.get("error"):
1560
+ return JSONResponse(
1561
+ {"error": "Google refused the sign-in.", "reason": "provider_error"},
1562
+ status_code=400,
1563
+ )
1564
+ code = request.query_params.get("code") or ""
1565
+ if not code:
1566
+ return JSONResponse(
1567
+ {"error": "Missing authorization code.", "reason": "code_missing"},
1568
+ status_code=400,
1569
+ )
1570
+ if flow["redirect_uri"] not in signup_config.redirect_uris:
1571
+ return JSONResponse(
1572
+ {"error": "Redirect URI is not allow-listed.",
1573
+ "reason": "redirect_uri_not_allowed"},
1574
+ status_code=400,
1575
+ )
1576
+ try:
1577
+ tokens = await run_in_threadpool(
1578
+ google_oidc.exchange_code,
1579
+ code=code,
1580
+ code_verifier=flow["code_verifier"],
1581
+ client_id=signup_config.google_client_id,
1582
+ client_secret=signup_config.google_client_secret,
1583
+ redirect_uri=flow["redirect_uri"],
1584
+ )
1585
+ jwks = await run_in_threadpool(google_oidc.get_jwks)
1586
+ try:
1587
+ claims = google_oidc.verify_id_token(
1588
+ tokens["id_token"],
1589
+ jwks=jwks,
1590
+ client_id=signup_config.google_client_id,
1591
+ nonce=flow["nonce"],
1592
+ )
1593
+ except google_oidc.OIDCError as exc:
1594
+ # Google rotates signing keys; a cached JWKS can lag by a `kid`.
1595
+ # Refetch once before refusing a token we might otherwise accept.
1596
+ if exc.reason != "unknown_key":
1597
+ raise
1598
+ google_oidc.clear_jwks_cache()
1599
+ jwks = await run_in_threadpool(google_oidc.get_jwks)
1600
+ claims = google_oidc.verify_id_token(
1601
+ tokens["id_token"],
1602
+ jwks=jwks,
1603
+ client_id=signup_config.google_client_id,
1604
+ nonce=flow["nonce"],
1605
+ )
1606
+ email = claims.get("email")
1607
+ if not isinstance(email, str) or not email.strip():
1608
+ raise google_oidc.OIDCError("claim_missing", "ID token has no email.")
1609
+ except google_oidc.OIDCError as exc:
1610
+ return JSONResponse(
1611
+ {"error": "Google sign-in could not be verified.", "reason": exc.reason},
1612
+ status_code=400,
1613
+ )
1614
+ tenant_target = _tenant_transfer_target(flow["return_to"])
1615
+ if tenant_target is not None:
1616
+ # This origin is the control plane for a tenant sign-in. The address
1617
+ # is verified; the tenant decides whether it belongs.
1618
+ return _tenant_transfer_redirect(
1619
+ email=email,
1620
+ subject=claims["sub"],
1621
+ name=claims.get("name"),
1622
+ picture=claims.get("picture"),
1623
+ tenant_target=tenant_target,
1624
+ source="google_callback",
1625
+ )
1626
+
1627
+ identity = signup_store.upsert_identity(
1628
+ subject=claims["sub"],
1629
+ email=email.strip().lower(),
1630
+ email_verified=claims.get("email_verified") is True,
1631
+ name=claims.get("name"),
1632
+ picture=claims.get("picture"),
1633
+ hosted_domain=claims.get("hd"),
1634
+ )
1635
+ raw, _session = signup_store.rotate_session(
1636
+ previous_raw=request.cookies.get(_SIGNUP_SESSION_COOKIE),
1637
+ identity_id=identity["id"],
1638
+ client_ip=_client_ip(request),
1639
+ user_agent=request.headers.get("user-agent"),
1640
+ days=signup_config.session_days,
1641
+ )
1642
+ _security_log.info("auth.callback action=control_session")
1643
+ response = RedirectResponse(flow["return_to"] or "/", status_code=302)
1644
+ response.set_cookie(
1645
+ _SIGNUP_SESSION_COOKIE,
1646
+ raw,
1647
+ max_age=signup_config.session_days * 24 * 60 * 60,
1648
+ **_session_cookie_attrs(request),
1649
+ )
1650
+ response.delete_cookie(_OIDC_FLOW_COOKIE, path="/")
1651
+ return response
1652
+
1653
+ async def google_sign_in_finish(request: Request):
1654
+ """Redeem a handoff token on this tenant origin and sign the person in."""
1655
+ host = _signup_host(request).split(":")[0].lower()
1656
+ transfer_key = signup_config.identity_transfer_key
1657
+ if not transfer_key:
1658
+ return JSONResponse(
1659
+ {"error": "Sign-in is not configured on this workspace.",
1660
+ "reason": "transfer_unconfigured"},
1661
+ status_code=503,
1662
+ )
1663
+ try:
1664
+ claims = identity_transfer.redeem(
1665
+ key=transfer_key,
1666
+ token=request.query_params.get("t"),
1667
+ audience=host,
1668
+ )
1669
+ except identity_transfer.TransferError as exc:
1670
+ return JSONResponse(
1671
+ {"error": "This sign-in link is invalid or has expired.",
1672
+ "reason": exc.reason},
1673
+ status_code=400,
1674
+ )
1675
+ try:
1676
+ with engine.begin() as conn:
1677
+ resolved = google_login.resolve_verified_email(
1678
+ conn,
1679
+ email=claims["email"],
1680
+ subject=claims["sub"],
1681
+ name=claims.get("name"),
1682
+ picture=claims.get("picture"),
1683
+ workspace_slug=host.split(".")[0],
1684
+ )
1685
+ except Exception:
1686
+ logger.exception("google sign-in could not be resolved")
1687
+ return JSONResponse(
1688
+ {"error": "Sign-in could not be completed.", "reason": "resolve_failed"},
1689
+ status_code=500,
1690
+ )
1691
+ _security_log.info(
1692
+ "auth.finish host=%s action=%s", host, resolved["action"]
1693
+ )
1694
+ if resolved["action"] == google_login.ACTION_DENIED:
1695
+ return JSONResponse(
1696
+ {"error": "This Google account is not a member of this workspace.",
1697
+ "reason": resolved.get("reason", "denied")},
1698
+ status_code=403,
1699
+ )
1700
+ session_token, _details = store.create_session_for_membership(
1701
+ resolved["identity_id"], resolved["user_id"], resolved["organization_id"]
1702
+ )
1703
+ if not session_token:
1704
+ return JSONResponse(
1705
+ {"error": "Sign-in could not be completed.", "reason": "session_failed"},
1706
+ status_code=500,
1707
+ )
1708
+ response = RedirectResponse(_safe_return_to(request.query_params.get("to")), status_code=302)
1709
+ response.set_cookie(
1710
+ "hoja_session",
1711
+ session_token,
1712
+ max_age=14 * 24 * 60 * 60,
1713
+ **_session_cookie_attrs(request),
1714
+ )
1715
+ return response
1716
+
1717
+ def _signup_workspace_payload(row: dict) -> dict:
1718
+ """One requester's own workspace/request state, safe for the page."""
1719
+ slug = str(row.get("slug") or "")
1720
+ status = str(row.get("status") or "eligible")
1721
+ workspace_url = None
1722
+ sign_in_url = None
1723
+ if status == "active":
1724
+ workspace_url = f"https://{slug}.{signup_config.tenant_base_domain}"
1725
+ sign_in_url = f"{workspace_url}/auth/google/start?return_to=%2F"
1726
+ message = "Your workspace is ready."
1727
+ elif status == "provisioning":
1728
+ message = "Your workspace is being created."
1729
+ elif status == "failed":
1730
+ message = "We could not finish creating this workspace."
1731
+ else:
1732
+ message = "Your workspace request is queued for creation."
1733
+ return {
1734
+ "slug": slug,
1735
+ "status": status,
1736
+ "workspaceUrl": workspace_url,
1737
+ "signInUrl": sign_in_url,
1738
+ "message": message,
1739
+ }
1740
+
1741
+ async def signup_endpoint(request: Request):
1742
+ if request.method == "GET":
1743
+ identity = _signup_identity(request)
1744
+ payload = {
1745
+ "state": "google_verified" if identity else "anonymous",
1746
+ "googleVerified": bool(identity),
1747
+ "humanVerified": False,
1748
+ "email": (identity or {}).get("email"),
1749
+ }
1750
+ if identity is not None:
1751
+ row = signup_store.latest_eligibility_for_identity(identity["identity_id"])
1752
+ if row is not None:
1753
+ payload["workspace"] = _signup_workspace_payload(row)
1754
+ return JSONResponse(payload, headers={"cache-control": "no-store"})
1755
+ if not _same_origin(request.headers.get("origin"), request.headers):
1756
+ return JSONResponse(
1757
+ {"ok": False, "reason": CROSS_SITE_REQUEST,
1758
+ "message": "Cross-site request rejected."},
1759
+ status_code=403,
1760
+ )
1761
+ body, body_error = await _read_json_object(request, _SIGNUP_BODY_LIMIT)
1762
+ if body_error is not None:
1763
+ return JSONResponse(
1764
+ {"ok": False, "reason": INVALID_REQUEST,
1765
+ "message": body_error.body.decode("utf-8", "replace")},
1766
+ status_code=body_error.status_code,
1767
+ )
1768
+ token = body.get("turnstileToken")
1769
+ if token is None:
1770
+ token = body.get("turnstile_token")
1771
+ decision = signup_gate.evaluate(
1772
+ identity=_signup_identity(request),
1773
+ slug=body.get("slug"),
1774
+ turnstile_token=token if isinstance(token, str) else None,
1775
+ client_ip=_client_ip(request),
1776
+ )
1777
+ return JSONResponse(decision.as_dict(), status_code=decision.status_code)
1778
+
1779
+ async def signup_status(request: Request):
1780
+ """The signed-in requester's own workspace state, for the sign-up page.
1781
+
1782
+ Deliberately not public: the sign-up session identifies the requester,
1783
+ and the slug must belong to that identity. It answers no secrets and no
1784
+ other person's queue position.
1785
+ """
1786
+ identity = _signup_identity(request)
1787
+ if identity is None:
1788
+ return JSONResponse(
1789
+ {"ok": False, "reason": "not_authenticated"}, status_code=401
1790
+ )
1791
+ slug = (request.query_params.get("slug") or "").strip().lower()
1792
+ if not slug or len(slug) > 63:
1793
+ return JSONResponse({"ok": False, "reason": "invalid_slug"}, status_code=400)
1794
+ row = signup_store.eligibility_for(identity["identity_id"], slug)
1795
+ if row is None:
1796
+ return JSONResponse({"ok": False, "reason": "not_found"}, status_code=404)
1797
+ return JSONResponse(
1798
+ {"ok": True, **_signup_workspace_payload(row)},
1799
+ headers={"cache-control": "no-store"},
1800
+ )
1801
+
1802
+ async def signup_logout(request: Request):
1803
+ if not _same_origin(request.headers.get("origin"), request.headers):
1804
+ return JSONResponse({"error": "Cross-site request rejected."}, status_code=403)
1805
+ _security_log.info("auth.logout scope=signup")
1806
+ signup_store.revoke_session(request.cookies.get(_SIGNUP_SESSION_COOKIE))
1807
+ response = JSONResponse({"status": "logged_out"})
1808
+ response.delete_cookie(_SIGNUP_SESSION_COOKIE, path="/")
1809
+ return response
1810
+
1811
+ # ---- Attachment file uploads (images/files/videos for issue attachments)
1812
+ _UPLOAD_MAX_BYTES = 10 * 1024 * 1024
1813
+ _UPLOAD_TYPE_PREFIXES = ("image/", "video/")
1814
+ _UPLOAD_TYPE_EXACT = {"application/pdf", "text/plain", "text/markdown"}
1815
+
1816
+ def _uploads_dir() -> Path:
1817
+ from hoja_server.db import default_db_dir
1818
+ d = default_db_dir() / "uploads"
1819
+ d.mkdir(parents=True, exist_ok=True)
1820
+ return d
1821
+
1822
+ async def upload_create(request: Request):
1823
+ uid, org, _identity_id, _browser_session = _auth(request)
1824
+ if not uid:
1825
+ return JSONResponse({"error": "Authentication required"}, status_code=401)
1826
+ csrf = _cookie_csrf_error(request, json_only=False)
1827
+ if csrf:
1828
+ return csrf
1829
+ try:
1830
+ form = await request.form()
1831
+ except Exception:
1832
+ return JSONResponse({"error": "Invalid multipart body"}, status_code=400)
1833
+ upload = form.get("file")
1834
+ if upload is None or not hasattr(upload, "read"):
1835
+ return JSONResponse({"error": "Missing 'file' field"}, status_code=400)
1836
+ content_type = (getattr(upload, "content_type", "") or "").split(";")[0].strip().lower()
1837
+ allowed = content_type in _UPLOAD_TYPE_EXACT or any(
1838
+ content_type.startswith(p) for p in _UPLOAD_TYPE_PREFIXES)
1839
+ if not allowed:
1840
+ return JSONResponse({"error": "File type not allowed"}, status_code=415)
1841
+ body = await upload.read()
1842
+ if len(body) > _UPLOAD_MAX_BYTES:
1843
+ return JSONResponse({"error": "File too large (10 MB max)"}, status_code=413)
1844
+ original = (getattr(upload, "filename", "") or "file").split("/")[-1].split("\\")[-1]
1845
+ ext = "".join(c for c in Path(original).suffix.lower() if c.isalnum() or c == ".")[:12]
1846
+ file_id = secrets.token_hex(16)
1847
+ stored = _uploads_dir() / f"{file_id}{ext}"
1848
+ stored.write_bytes(body)
1849
+ (_uploads_dir() / f"{file_id}.json").write_text(
1850
+ json.dumps({"org": org, "filename": original[:120],
1851
+ "content_type": content_type, "size": len(body)}))
1852
+ return JSONResponse({"url": f"/api/uploads/{file_id}",
1853
+ "title": original[:120] or "file"})
1854
+
1855
+ async def upload_serve(request: Request):
1856
+ uid, org, _identity_id, _browser_session = _auth(request)
1857
+ if not uid:
1858
+ return JSONResponse({"error": "Authentication required"}, status_code=401)
1859
+ file_id = request.path_params.get("file_id", "")
1860
+ if not file_id.replace("_", "").replace("-", "").isalnum() or len(file_id) > 64:
1861
+ return JSONResponse({"error": "Not found"}, status_code=404)
1862
+ meta_path = _uploads_dir() / f"{file_id}.json"
1863
+ try:
1864
+ meta = json.loads(meta_path.read_text())
1865
+ except (OSError, ValueError):
1866
+ return JSONResponse({"error": "Not found"}, status_code=404)
1867
+ if meta.get("org") != org:
1868
+ return JSONResponse({"error": "Not found"}, status_code=404)
1869
+ # An uploaded file inherits its issue's team visibility: knowing the (random)
1870
+ # file id is not authority to read a private team's material.
1871
+ if not store.upload_visible(org, uid, file_id):
1872
+ return JSONResponse({"error": "Not found"}, status_code=404)
1873
+ candidates = [p for p in _uploads_dir().glob(f"{file_id}.*")
1874
+ if p.suffix != ".json" and p.name != f"{file_id}.json"]
1875
+ if not candidates:
1876
+ return JSONResponse({"error": "Not found"}, status_code=404)
1877
+ return FileResponse(
1878
+ candidates[0],
1879
+ media_type=meta.get("content_type") or "application/octet-stream",
1880
+ filename=meta.get("filename") or "file",
1881
+ content_disposition_type="inline",
1882
+ )
1883
+
1884
+ def _sync_meta(request: Request, uid: str, org: str, identity_id, is_browser: bool) -> dict:
1885
+ context = {"request": request, "store": store, "cache": {}, "writer": writer,
1886
+ "org_id": org, "user_id": uid, "identity_id": identity_id,
1887
+ "browser_session": is_browser,
1888
+ "access": getattr(request.state, "api_key_access", "read_write")}
1889
+ _ok, result = graphql_sync(_schema, {"query": sync.META_QUERY}, context_value=context,
1890
+ error_formatter=_format_graphql_error)
1891
+ if result.get("errors"):
1892
+ raise RuntimeError(result["errors"][0].get("message", "metadata query failed"))
1893
+ return {**result["data"], "users": sync.org_users(store, org)}
1894
+
1895
+ def _sync_json(body: dict, **kwargs) -> Response:
1896
+ return Response(json.dumps(body, separators=(",", ":")), media_type="application/json", **kwargs)
1897
+
1898
+ async def sync_bootstrap(request: Request):
1899
+ uid, org, identity_id, is_browser = await run_in_threadpool(_auth_sync, request)
1900
+ if uid: # resolved in a worker thread: its context copy is gone, bind here
1901
+ tenant_context.bind(org)
1902
+ if not uid:
1903
+ return JSONResponse({"error": "Authentication required"}, status_code=401)
1904
+ try:
1905
+ closed_days = int(request.query_params.get("closedDays", sync.DEFAULT_CLOSED_DAYS))
1906
+ except ValueError:
1907
+ return _bad_request("closedDays must be an integer.")
1908
+ if not 0 <= closed_days <= sync.MAX_CLOSED_DAYS:
1909
+ return _bad_request(f"closedDays must be between 0 and {sync.MAX_CLOSED_DAYS}.")
1910
+
1911
+ def validator():
1912
+ # Seq first: anything committed while the snapshot is read is replayed by the next delta.
1913
+ seq = store.latest_change_seq(org)
1914
+ cutoff = sync.closed_cutoff(closed_days)
1915
+ visible = store.visible_team_ids(org, uid)
1916
+ key = sync.issues_key(org, seq, cutoff, visible)
1917
+ return seq, cutoff, visible, key, sync.snapshot_etag(uid, key)
1918
+
1919
+ seq, cutoff, visible, key, etag = await run_in_threadpool(validator)
1920
+ headers = {"ETag": etag, "Cache-Control": "private, no-cache",
1921
+ "Vary": "Cookie, Authorization, Accept-Encoding"}
1922
+ if_none_match = request.headers.get("if-none-match") or ""
1923
+ if etag in [t.strip() for t in if_none_match.split(",")]:
1924
+ return Response(status_code=304, headers=headers)
1925
+
1926
+ async def build_issues():
1927
+ # Derive from the previous snapshot of the same (org, window, visibility)
1928
+ # plus the rows the realtime feed already fetched, instead of re-reading
1929
+ # every open issue after each write.
1930
+ lineage = (org, cutoff, key[3])
1931
+ prev = issue_lineage.get(lineage)
1932
+ rows = None
1933
+ if prev is not None and prev[0] < seq and await hub.wait_head(org, seq):
1934
+ changes = hub.issue_changes(org, prev[0], seq)
1935
+ if changes is not None:
1936
+ prev_rows = prev[1]
1937
+ async with gql_slots:
1938
+ rows = await run_in_threadpool(lambda: sync.derive_issues(
1939
+ prev_rows, changes, visible, cutoff, sync.closed_state_ids(store, org)))
1940
+ elif prev is not None and prev[0] == seq:
1941
+ rows = prev[1]
1942
+ hub.stats["snapshot_derived" if rows is not None else "snapshot_full"] += 1
1943
+ async with gql_slots:
1944
+ if rows is None:
1945
+ rows = await run_in_threadpool(sync.bootstrap_issues, store, org, uid, cutoff)
1946
+ data = await run_in_threadpool(lambda: json.dumps(rows, separators=(",", ":")).encode())
1947
+ current = issue_lineage.get(lineage)
1948
+ if current is None or current[0] < seq:
1949
+ issue_lineage[lineage] = (seq, rows)
1950
+ while len(issue_lineage) > 64:
1951
+ issue_lineage.pop(next(iter(issue_lineage)))
1952
+ return data
1953
+
1954
+ async def build_body():
1955
+ issues_json = await issue_snapshots.get(key, build_issues)
1956
+
1957
+ def assemble():
1958
+ head = {"v": sync.SYNC_VERSION, "seq": seq, "closedCutoff": cutoff,
1959
+ "scope": sync.sync_scope(org, uid),
1960
+ "meta": _sync_meta(request, uid, org, identity_id, is_browser),
1961
+ "columns": sync.ISSUE_COLUMNS}
1962
+ raw = json.dumps(head, separators=(",", ":")).encode()[:-1] + b',"issues":' + issues_json + b"}"
1963
+ return raw, gzip.compress(raw, 6)
1964
+
1965
+ async with gql_slots:
1966
+ return await run_in_threadpool(assemble)
1967
+
1968
+ raw, packed = await body_snapshots.get(etag, build_body)
1969
+ if "gzip" in request.headers.get("accept-encoding", ""):
1970
+ return Response(packed, media_type="application/json",
1971
+ headers={**headers, "Content-Encoding": "gzip"})
1972
+ return Response(raw, media_type="application/json", headers=headers)
1973
+
1974
+ async def sync_delta(request: Request):
1975
+ uid, org, identity_id, is_browser = await run_in_threadpool(_auth_sync, request)
1976
+ if uid: # resolved in a worker thread: its context copy is gone, bind here
1977
+ tenant_context.bind(org)
1978
+ if not uid:
1979
+ return JSONResponse({"error": "Authentication required"}, status_code=401)
1980
+ try:
1981
+ after = int(request.query_params.get("after", ""))
1982
+ except ValueError:
1983
+ return _bad_request("after must be an integer.")
1984
+ if not 0 <= after <= _MAX_SEQ:
1985
+ return _bad_request("after is out of range.")
1986
+ scope = request.query_params.get("scope")
1987
+
1988
+ async def meta_for(meta_seq):
1989
+ async def build():
1990
+ async with gql_slots:
1991
+ return await run_in_threadpool(_sync_meta, request, uid, org, identity_id, is_browser)
1992
+ return await meta_cache.get((org, uid, identity_id, meta_seq), build)
1993
+
1994
+ delta = None
1995
+ if scope is None or scope == sync.sync_scope(org, uid):
1996
+ # Served from the realtime ring: after a broadcast every client pulls at
1997
+ # once, and none of them needs to touch the database.
1998
+ delta = await hub.delta(org, uid, after)
1999
+ if delta is not None and delta.get("meta"):
2000
+ delta["meta"] = await meta_for(delta["seq"])
2001
+ if delta is None:
2002
+ def build():
2003
+ return sync.build_delta(store, org, uid, after, scope)
2004
+
2005
+ async with gql_slots:
2006
+ delta = await run_in_threadpool(build)
2007
+ if delta.get("meta"):
2008
+ delta["meta"] = await meta_for(delta["seq"])
2009
+ return _sync_json(delta, headers={"Cache-Control": "no-store"})
2010
+
2011
+ async def health(request: Request):
2012
+ return JSONResponse({"status": "ok"})
2013
+
2014
+ async def ready(request: Request):
2015
+ try:
2016
+ with engine.connect() as conn:
2017
+ conn.execute(text("SELECT 1")).scalar_one()
2018
+ from hoja_server.db import inspect
2019
+
2020
+ if not inspect(engine).has_table("schema_revision"):
2021
+ return JSONResponse({"status": "unavailable", "reason": "schema_outdated"}, status_code=503)
2022
+ if not schema_is_current(engine):
2023
+ return JSONResponse(
2024
+ {"status": "unavailable", "reason": "schema_outdated"},
2025
+ status_code=503,
2026
+ )
2027
+ except Exception:
2028
+ return JSONResponse({"status": "unavailable"}, status_code=503)
2029
+ return JSONResponse({"status": "ready"})
2030
+
2031
+ async def web_index(request: Request):
2032
+ index = _WEB_ROOT / "index.html"
2033
+ if not index.is_file():
2034
+ return HTMLResponse(_UNBUILT_HTML, status_code=503)
2035
+ return FileResponse(index)
2036
+
2037
+ async def web_asset(request: Request):
2038
+ name = request.path_params["name"]
2039
+ asset = (_WEB_ROOT / "assets" / name).resolve()
2040
+ if _WEB_ROOT not in asset.parents or not asset.is_file():
2041
+ return JSONResponse({"error": "Not found"}, status_code=404)
2042
+ return FileResponse(asset)
2043
+
2044
+ async def web_brand_mark(request: Request):
2045
+ root = _WEB_ROOT.resolve()
2046
+ asset = (root / BRAND_MARK).resolve()
2047
+ if root not in asset.parents or not asset.is_file():
2048
+ return JSONResponse({"error": "Not found"}, status_code=404)
2049
+ return FileResponse(asset, media_type="image/svg+xml")
2050
+
2051
+ async def web_fallback(request: Request):
2052
+ index = _WEB_ROOT / "index.html"
2053
+ if not index.is_file():
2054
+ return HTMLResponse(_UNBUILT_HTML, status_code=503)
2055
+ return FileResponse(index)
2056
+
2057
+ def _sqlite_analyze():
2058
+ # Without planner statistics SQLite prefers the (single-valued, in a
2059
+ # one-workspace database) organization_id index over the id/identifier
2060
+ # indexes and scans every issue for a single-issue lookup.
2061
+ with engine.begin() as conn:
2062
+ conn.exec_driver_sql("PRAGMA analysis_limit=1000")
2063
+ conn.exec_driver_sql("ANALYZE")
2064
+
2065
+ async def _sqlite_maintenance():
2066
+ while True:
2067
+ try:
2068
+ await asyncio.to_thread(_sqlite_analyze)
2069
+ except Exception:
2070
+ logging.getLogger("hoja_server").warning("SQLite ANALYZE failed", exc_info=True)
2071
+ await asyncio.sleep(6 * 3600)
2072
+
2073
+ @asynccontextmanager
2074
+ async def lifespan(app):
2075
+ nonlocal mcp_asgi, durable_agent
2076
+ # Each TestClient/server lifespan gets a fresh SDK session manager;
2077
+ # the SDK manager is intentionally single-use after shutdown.
2078
+ from hoja_server.mcp_oauth import HojaOAuthProvider, build_server
2079
+
2080
+ runtime_server = build_server(
2081
+ HojaOAuthProvider(engine, store, trusted_proxy=trust_proxy), public_host=public_host
2082
+ )
2083
+ runtime_app = runtime_server.streamable_http_app(
2084
+ streamable_http_path="/", stateless_http=True,
2085
+ transport_security=TransportSecuritySettings(
2086
+ enable_dns_rebinding_protection=True,
2087
+ allowed_hosts=[public_host.strip(), public_host.strip() + ":*"],
2088
+ ),
2089
+ )
2090
+ mcp_asgi = runtime_app
2091
+ from concurrent.futures import ThreadPoolExecutor
2092
+ asyncio.get_running_loop().set_default_executor(
2093
+ ThreadPoolExecutor(max_workers=32, thread_name_prefix="hoja"))
2094
+ await hub.ensure_started()
2095
+ meeting_hub.start()
2096
+ maintenance = asyncio.create_task(_sqlite_maintenance()) if engine.dialect.name == "sqlite" else None
2097
+ async with runtime_app.router.lifespan_context(runtime_app):
2098
+ if agent_dbos_url := os.environ.get("HOJA_AGENT_DBOS_URL"):
2099
+ from dbos import DBOS
2100
+
2101
+ # Imported before launch: DBOS registers workflows at import and recovers them at launch.
2102
+ from hoja_server import agent_durable
2103
+
2104
+ agent_durable.configure(store, writer, _schema)
2105
+ DBOS(config={"name": "hoja-agent", "system_database_url": agent_dbos_url})
2106
+ DBOS.launch()
2107
+ durable_agent = agent_durable
2108
+ try:
2109
+ yield
2110
+ finally:
2111
+ durable_agent = None
2112
+ DBOS.destroy()
2113
+ agent_durable.shutdown()
2114
+ else:
2115
+ yield
2116
+ await hub.stop()
2117
+ await meeting_hub.close_all()
2118
+ if sfu is not None:
2119
+ await sfu.aclose()
2120
+ if maintenance is not None:
2121
+ maintenance.cancel()
2122
+
2123
+ async def _malformed_json_handler(request: Request, exc: Exception):
2124
+ return JSONResponse({"error": "Malformed JSON body."}, status_code=400)
2125
+
2126
+ app = Starlette(
2127
+ routes=[
2128
+ Route("/graphql", graphql_server, methods=["POST", "GET"]),
2129
+ Route("/api/agent/chat", agent_chat_server, methods=["POST"]),
2130
+ Route("/api/agent/threads/get", agent_threads_list, methods=["GET"]),
2131
+ Route("/api/agent/threads/create", agent_threads_create, methods=["POST"]),
2132
+ Route("/api/agent/threads/get/{thread_id}", agent_thread_get, methods=["GET"]),
2133
+ Route("/api/agent/threads/update/{thread_id}", agent_thread_update, methods=["PATCH"]),
2134
+ Route("/api/agent/threads/delete/{thread_id}", agent_thread_delete, methods=["DELETE"]),
2135
+ *connector_routes(engine, store, _auth),
2136
+ *meeting_routes(
2137
+ engine, meeting_service, meeting_hub, auth=_auth,
2138
+ csrf=lambda request: _cookie_csrf_error(request, json_only=True),
2139
+ read_json=_read_json_object, client_ip=_client_ip, same_origin=_same_origin, sfu=sfu),
2140
+ WebSocketRoute("/ws", realtime_socket),
2141
+ Route("/auth/setup", auth_setup, methods=["GET", "POST"]),
2142
+ Route("/auth/invite/accept", auth_invite_accept, methods=["POST"]),
2143
+ Route("/onboarding/status", onboarding_status, methods=["GET"]),
2144
+ Route("/onboarding/bootstrap", onboarding_bootstrap, methods=["POST"]),
2145
+ Route("/auth/login", auth_login, methods=["POST"]),
2146
+ Route("/auth/workspaces", auth_workspaces, methods=["POST"]),
2147
+ Route("/auth/logout", auth_logout, methods=["POST"]),
2148
+ Route("/auth/me", auth_me, methods=["GET"]),
2149
+ Route("/auth/google/start", google_sign_in_start, methods=["GET"]),
2150
+ Route("/auth/google/callback", google_sign_in_callback, methods=["GET"]),
2151
+ Route("/auth/google/finish", google_sign_in_finish, methods=["GET"]),
2152
+ Route("/auth/google/logout", signup_logout, methods=["POST"]),
2153
+ Route("/api/signup/config", signup_public_config, methods=["GET"]),
2154
+ Route("/api/signup/status", signup_status, methods=["GET"]),
2155
+ Route("/api/signup", signup_endpoint, methods=["GET", "POST"]),
2156
+ Route("/api/uploads", upload_create, methods=["POST"]),
2157
+ Route("/api/uploads/{file_id}", upload_serve, methods=["GET"]),
2158
+ Route("/sync/bootstrap", sync_bootstrap, methods=["GET"]),
2159
+ Route("/sync/delta", sync_delta, methods=["GET"]),
2160
+ Route("/health", health, methods=["GET"]),
2161
+ Route("/ready", ready, methods=["GET"]),
2162
+ Route(
2163
+ "/.well-known/oauth-authorization-server/mcp",
2164
+ authorization_metadata_endpoint,
2165
+ methods=["GET", "OPTIONS"],
2166
+ ),
2167
+ Route(
2168
+ "/.well-known/oauth-protected-resource/mcp",
2169
+ resource_metadata_endpoint,
2170
+ methods=["GET", "OPTIONS"],
2171
+ ),
2172
+ Mount("/mcp", app=mcp_endpoint),
2173
+ Route("/", web_index, methods=["GET"]),
2174
+ Route("/assets/{name:path}", web_asset, methods=["GET"]),
2175
+ Route(f"/{BRAND_MARK}", web_brand_mark, methods=["GET"]),
2176
+ Route("/{path:path}", web_fallback, methods=["GET"]),
2177
+ ],
2178
+ lifespan=lifespan,
2179
+ )
2180
+ app.state.realtime = hub
2181
+ app.state.meetings = meeting_hub
2182
+ app.add_middleware(_SecurityHeaders)
2183
+ # Compress JSON and static assets; SSE streams are excluded by Starlette.
2184
+ app.add_middleware(GZipMiddleware, minimum_size=1024, compresslevel=6)
2185
+ # Outermost: enumerated pre-tenant paths run in system context; every other
2186
+ # request has no tenant until _auth binds one (fail closed under RLS).
2187
+ app.add_middleware(tenant_context.TenantContextMiddleware)
2188
+ app.add_exception_handler(json.JSONDecodeError, _malformed_json_handler)
2189
+ return app