hoja-cli 0.21.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- VERSION +1 -0
- google_workspace/__init__.py +19 -0
- google_workspace/client.py +253 -0
- google_workspace/config.py +39 -0
- google_workspace/errors.py +19 -0
- google_workspace/mcp_server.py +100 -0
- google_workspace/oauth.py +131 -0
- google_workspace/principal.py +83 -0
- google_workspace/py.typed +0 -0
- google_workspace/tools.py +64 -0
- google_workspace/writes.py +44 -0
- hoja/__init__.py +29 -0
- hoja/__main__.py +6 -0
- hoja/auth.py +42 -0
- hoja/cli.py +161 -0
- hoja/cli_state.py +55 -0
- hoja/client.py +268 -0
- hoja/commands/__init__.py +4 -0
- hoja/commands/auth_cmd.py +271 -0
- hoja/commands/comment.py +149 -0
- hoja/commands/cycle.py +75 -0
- hoja/commands/init.py +108 -0
- hoja/commands/issue.py +398 -0
- hoja/commands/label.py +163 -0
- hoja/commands/memory.py +240 -0
- hoja/commands/project.py +56 -0
- hoja/commands/raw.py +50 -0
- hoja/commands/team.py +102 -0
- hoja/commands/update.py +162 -0
- hoja/config.py +362 -0
- hoja/errors.py +107 -0
- hoja/filters.py +150 -0
- hoja/graphql/__init__.py +5 -0
- hoja/graphql/fragments.py +138 -0
- hoja/graphql/mutations.py +160 -0
- hoja/graphql/queries.py +245 -0
- hoja/mcp/__init__.py +27 -0
- hoja/mcp/content.py +151 -0
- hoja/mcp/prompts.py +298 -0
- hoja/mcp/resources.py +213 -0
- hoja/mcp/server.py +189 -0
- hoja/memory_board.py +370 -0
- hoja/models/__init__.py +37 -0
- hoja/models/base.py +64 -0
- hoja/models/cycle.py +32 -0
- hoja/models/enums.py +62 -0
- hoja/models/issue.py +99 -0
- hoja/models/label.py +17 -0
- hoja/models/project.py +60 -0
- hoja/models/team.py +31 -0
- hoja/models/user.py +32 -0
- hoja/models/workflow.py +65 -0
- hoja/output.py +410 -0
- hoja/skill_content/commands.md +222 -0
- hoja/skill_content/examples.md +193 -0
- hoja/skill_content/filters.md +101 -0
- hoja/skill_content/output-formats.md +92 -0
- hoja/skill_content/overview.md +123 -0
- hoja/skill_content/workflows.md +174 -0
- hoja_cli-0.21.4.dist-info/METADATA +279 -0
- hoja_cli-0.21.4.dist-info/RECORD +107 -0
- hoja_cli-0.21.4.dist-info/WHEEL +4 -0
- hoja_cli-0.21.4.dist-info/entry_points.txt +4 -0
- hoja_cli-0.21.4.dist-info/licenses/LICENSE +21 -0
- hoja_server/README.md +135 -0
- hoja_server/__init__.py +11 -0
- hoja_server/abac.py +116 -0
- hoja_server/agent_chat.py +280 -0
- hoja_server/agent_conversations.py +91 -0
- hoja_server/agent_durable.py +332 -0
- hoja_server/agent_prompt.py +117 -0
- hoja_server/agent_threads.py +96 -0
- hoja_server/agent_uploads.py +60 -0
- hoja_server/app.py +2189 -0
- hoja_server/cadence.py +231 -0
- hoja_server/cli.py +191 -0
- hoja_server/cloudflare_realtime.py +110 -0
- hoja_server/comment_policy.py +70 -0
- hoja_server/connector_actions.py +119 -0
- hoja_server/connectors_api.py +375 -0
- hoja_server/db.py +1816 -0
- hoja_server/denials.py +18 -0
- hoja_server/deployment.py +28 -0
- hoja_server/email_adapter.py +94 -0
- hoja_server/google_login.py +217 -0
- hoja_server/google_oidc.py +342 -0
- hoja_server/identity_transfer.py +210 -0
- hoja_server/mcp_oauth.py +623 -0
- hoja_server/mcp_tools.py +579 -0
- hoja_server/meeting_policy.py +179 -0
- hoja_server/meetings.py +1332 -0
- hoja_server/meetings_api.py +909 -0
- hoja_server/model_providers.py +205 -0
- hoja_server/realtime.py +690 -0
- hoja_server/resolvers.py +1281 -0
- hoja_server/schema.graphql +477 -0
- hoja_server/schema_sdl.py +8 -0
- hoja_server/secrets_box.py +39 -0
- hoja_server/signup_config.py +292 -0
- hoja_server/signup_gate.py +393 -0
- hoja_server/signup_policy.py +97 -0
- hoja_server/signup_store.py +577 -0
- hoja_server/store.py +2179 -0
- hoja_server/sync.py +249 -0
- hoja_server/tenant_context.py +131 -0
- hoja_server/turnstile.py +81 -0
- hoja_server/writer.py +1262 -0
hoja_server/cadence.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""Pure team-local cycle boundary calculations for fixed weekly cadence."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from datetime import date, datetime, time, timedelta, timezone
|
|
6
|
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|
7
|
+
|
|
8
|
+
BOUNDARY_TIME = time(0, 1)
|
|
9
|
+
POLICY_VERSION = 1
|
|
10
|
+
DURATION_WEEKS = 1
|
|
11
|
+
COOLDOWN_WEEKS = 0
|
|
12
|
+
UPCOMING_COUNT = 2
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class CadenceInputError(ValueError):
|
|
16
|
+
"""Invalid timezone, weekday, or local boundary in cadence settings."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class CycleInterval:
|
|
21
|
+
starts_at: datetime
|
|
22
|
+
ends_at: datetime
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _local_boundary(day: date, zone: ZoneInfo) -> datetime:
|
|
26
|
+
"""Resolve 00:01 strictly; reject DST gaps and folds instead of guessing."""
|
|
27
|
+
naive = datetime.combine(day, BOUNDARY_TIME)
|
|
28
|
+
candidates = [naive.replace(tzinfo=zone, fold=fold) for fold in (0, 1)]
|
|
29
|
+
valid = [candidate for candidate in candidates
|
|
30
|
+
if candidate.astimezone(timezone.utc).astimezone(zone).replace(tzinfo=None) == naive]
|
|
31
|
+
unique_instants = {candidate.astimezone(timezone.utc) for candidate in valid}
|
|
32
|
+
if len(unique_instants) != 1:
|
|
33
|
+
reason = "nonexistent" if not unique_instants else "ambiguous"
|
|
34
|
+
raise CadenceInputError(f"Local cycle boundary {naive.isoformat()} is {reason} in {zone.key}.")
|
|
35
|
+
return valid[0]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def calculate_boundaries(
|
|
39
|
+
*, timezone_name: str, weekday: int, now: datetime | None = None,
|
|
40
|
+
upcoming_count: int = UPCOMING_COUNT,
|
|
41
|
+
) -> tuple[CycleInterval, ...]:
|
|
42
|
+
"""Return Current (when due) and upcoming weekly intervals in UTC.
|
|
43
|
+
|
|
44
|
+
weekday follows ``date.weekday()`` (Monday=0). Activation starts at today's
|
|
45
|
+
local 00:01; subsequent boundaries align to the chosen weekday. Intervals
|
|
46
|
+
are half-open and each endpoint is independently localized across DST.
|
|
47
|
+
"""
|
|
48
|
+
if not isinstance(weekday, int) or isinstance(weekday, bool) or not 0 <= weekday <= 6:
|
|
49
|
+
raise CadenceInputError("weekday must be an integer from 0 (Monday) through 6 (Sunday).")
|
|
50
|
+
if upcoming_count < 0:
|
|
51
|
+
raise CadenceInputError("upcoming_count cannot be negative.")
|
|
52
|
+
try:
|
|
53
|
+
zone = ZoneInfo(timezone_name)
|
|
54
|
+
except (ZoneInfoNotFoundError, TypeError, ValueError) as exc:
|
|
55
|
+
raise CadenceInputError(f"Unknown IANA timezone: {timezone_name!r}.") from exc
|
|
56
|
+
instant = now if now is not None else datetime.now(timezone.utc)
|
|
57
|
+
if instant.tzinfo is None or instant.utcoffset() is None:
|
|
58
|
+
raise CadenceInputError("now must be timezone-aware.")
|
|
59
|
+
local_now = instant.astimezone(zone)
|
|
60
|
+
today = local_now.date()
|
|
61
|
+
today_start = _local_boundary(today, zone)
|
|
62
|
+
if today_start <= local_now:
|
|
63
|
+
current_day = today
|
|
64
|
+
next_day = today + timedelta(days=(weekday - today.weekday()) % 7 or 7)
|
|
65
|
+
# At a selected weekday's 00:01 boundary, the current interval is full week.
|
|
66
|
+
if current_day.weekday() == weekday:
|
|
67
|
+
next_day = current_day + timedelta(days=7)
|
|
68
|
+
else:
|
|
69
|
+
# Before today's 00:01, do not backdate a Current cycle. If today
|
|
70
|
+
# is the selected weekday, its first full cycle starts at 00:01.
|
|
71
|
+
current_day = today if today.weekday() == weekday else today + timedelta(days=(weekday - today.weekday()) % 7)
|
|
72
|
+
next_day = current_day + timedelta(days=7)
|
|
73
|
+
start = _local_boundary(current_day, zone)
|
|
74
|
+
boundaries = [start, _local_boundary(next_day, zone)]
|
|
75
|
+
while len(boundaries) < upcoming_count + 2:
|
|
76
|
+
next_local_date = boundaries[-1].astimezone(zone).date() + timedelta(days=7)
|
|
77
|
+
boundaries.append(_local_boundary(next_local_date, zone))
|
|
78
|
+
utc_boundaries = [boundary.astimezone(timezone.utc) for boundary in boundaries]
|
|
79
|
+
return tuple(CycleInterval(a, b) for a, b in zip(utc_boundaries, utc_boundaries[1:]))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def validate_timezone(name: str) -> ZoneInfo:
|
|
83
|
+
try:
|
|
84
|
+
return ZoneInfo(name)
|
|
85
|
+
except (ZoneInfoNotFoundError, TypeError, ValueError) as exc:
|
|
86
|
+
raise CadenceInputError(f"Unknown IANA timezone: {name!r}.") from exc
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _rollover_cycle_issues(conn, org_id: str, team_id: str,
|
|
90
|
+
from_cycle_ids: list, to_cycle_id: str, timestamp: str) -> int:
|
|
91
|
+
"""Move unfinished issues from just-closed cycles into the new active cycle.
|
|
92
|
+
|
|
93
|
+
Mirrors Linear's "Issues rollover": open issues (unstarted/started states)
|
|
94
|
+
carry forward automatically; backlog, triage, completed, and canceled
|
|
95
|
+
issues stay behind. There is no way to keep an unfinished issue in a
|
|
96
|
+
closed cycle. Returns the number of issues moved.
|
|
97
|
+
"""
|
|
98
|
+
from sqlalchemy import and_, select, update
|
|
99
|
+
from hoja_server.db import issue, workflow_state
|
|
100
|
+
movable = (
|
|
101
|
+
select(issue.c.id)
|
|
102
|
+
.select_from(issue.join(workflow_state, workflow_state.c.id == issue.c.state_id))
|
|
103
|
+
.where(and_(
|
|
104
|
+
issue.c.organization_id == org_id,
|
|
105
|
+
issue.c.team_id == team_id,
|
|
106
|
+
issue.c.cycle_id.in_(from_cycle_ids),
|
|
107
|
+
issue.c.archived_at.is_(None),
|
|
108
|
+
workflow_state.c.type.in_(("unstarted", "started")),
|
|
109
|
+
))
|
|
110
|
+
)
|
|
111
|
+
result = conn.execute(
|
|
112
|
+
update(issue)
|
|
113
|
+
.where(issue.c.id.in_(movable))
|
|
114
|
+
.values(cycle_id=to_cycle_id, updated_at=timestamp)
|
|
115
|
+
)
|
|
116
|
+
return result.rowcount or 0
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def reconcile_team_cadence(conn, org_id: str, row, now: datetime) -> dict:
|
|
120
|
+
"""Within a caller-held team write transaction, ensure Current and two Upcoming.
|
|
121
|
+
|
|
122
|
+
A bounded reconciliation fails atomically on excessive downtime rather than
|
|
123
|
+
returning an apparently complete but stale schedule.
|
|
124
|
+
"""
|
|
125
|
+
from sqlalchemy import and_, select
|
|
126
|
+
from hoja_server.db import cycle, new_id, now_iso, team
|
|
127
|
+
|
|
128
|
+
zone_name = row.get("timezone") or "UTC"
|
|
129
|
+
validate_timezone(zone_name)
|
|
130
|
+
team_id = row["id"]
|
|
131
|
+
enabled = bool(row.get("cadence_enabled"))
|
|
132
|
+
if not enabled:
|
|
133
|
+
return {"enabled": False, "weekday": None, "timezone": zone_name,
|
|
134
|
+
"policyVersion": 1, "activeCycle": None, "upcomingCycles": []}
|
|
135
|
+
weekday = row.get("cadence_weekday")
|
|
136
|
+
if type(weekday) is not int or weekday not in range(7):
|
|
137
|
+
raise CadenceInputError("Team cadence weekday is invalid.")
|
|
138
|
+
if (row.get("cadence_policy_version") != POLICY_VERSION or
|
|
139
|
+
row.get("cadence_duration_weeks") != DURATION_WEEKS or
|
|
140
|
+
row.get("cadence_cooldown_weeks") != COOLDOWN_WEEKS or
|
|
141
|
+
row.get("cadence_upcoming_count") != UPCOMING_COUNT):
|
|
142
|
+
raise CadenceInputError("Unsupported team cycle policy; review settings before retrying.")
|
|
143
|
+
anchor_text = row.get("cadence_anchor_at")
|
|
144
|
+
if not anchor_text:
|
|
145
|
+
raise CadenceInputError("Team cycle anchor is missing.")
|
|
146
|
+
anchor = datetime.fromisoformat(anchor_text)
|
|
147
|
+
if anchor.tzinfo is None or now.tzinfo is None:
|
|
148
|
+
raise CadenceInputError("Cadence timestamps must be timezone-aware.")
|
|
149
|
+
current = now.astimezone(timezone.utc)
|
|
150
|
+
initial = calculate_boundaries(timezone_name=zone_name, weekday=weekday, now=anchor)
|
|
151
|
+
initial_start = initial[0].starts_at
|
|
152
|
+
before_start = current < initial_start
|
|
153
|
+
# Subsequent windows are calculated from local calendar dates, never 168 UTC hours.
|
|
154
|
+
local_zone = validate_timezone(zone_name)
|
|
155
|
+
start = initial[0].starts_at
|
|
156
|
+
first_end = initial[0].ends_at
|
|
157
|
+
boundaries = [start, first_end]
|
|
158
|
+
max_intervals = 256
|
|
159
|
+
while boundaries[-1] <= current:
|
|
160
|
+
if len(boundaries) >= max_intervals:
|
|
161
|
+
raise CadenceInputError("Cycle catch-up exceeds 255 intervals; manual review is required.")
|
|
162
|
+
previous_day = boundaries[-1].astimezone(local_zone).date()
|
|
163
|
+
next_day = previous_day + timedelta(days=7)
|
|
164
|
+
boundaries.append(_local_boundary(next_day, local_zone).astimezone(timezone.utc))
|
|
165
|
+
# Before the initial boundary, first two intervals are Upcoming. Otherwise
|
|
166
|
+
# retain one active and two future slots; elapsed periods stay bounded.
|
|
167
|
+
for _ in range(1 if before_start else 2):
|
|
168
|
+
previous_day = boundaries[-1].astimezone(local_zone).date()
|
|
169
|
+
boundaries.append(_local_boundary(previous_day + timedelta(days=7), local_zone).astimezone(timezone.utc))
|
|
170
|
+
# Boundaries contain the current window (if due) and two upcoming slots.
|
|
171
|
+
intervals = list(zip(boundaries, boundaries[1:]))
|
|
172
|
+
persisted = conn.execute(select(cycle).where(and_(cycle.c.organization_id == org_id,
|
|
173
|
+
cycle.c.team_id == team_id)).order_by(cycle.c.number)).mappings().all()
|
|
174
|
+
if any(r["cadence_boundary_at"] is None for r in persisted):
|
|
175
|
+
raise CadenceInputError("Existing unmanaged cycles require manual reconciliation.")
|
|
176
|
+
# A stale clock or delayed request must never demote the persisted Current
|
|
177
|
+
# pointer or rewrite completed history. Fail before any schedule insert.
|
|
178
|
+
pointer = row.get("active_cycle_id")
|
|
179
|
+
if pointer:
|
|
180
|
+
pointed = next((r for r in persisted if r["id"] == pointer), None)
|
|
181
|
+
if pointed is None:
|
|
182
|
+
raise CadenceInputError("Active cycle pointer is missing from this team.")
|
|
183
|
+
if current < datetime.fromisoformat(pointed["starts_at"]):
|
|
184
|
+
raise CadenceInputError("Clock precedes the active cycle; retry after correcting the clock.")
|
|
185
|
+
if len(persisted) > len(intervals):
|
|
186
|
+
# Retain already generated future slots; their starts must continue
|
|
187
|
+
# the same weekly local calendar cadence without changing past data.
|
|
188
|
+
for r in persisted[len(intervals):]:
|
|
189
|
+
prior_end = intervals[-1][1]
|
|
190
|
+
next_end_day = prior_end.astimezone(local_zone).date() + timedelta(days=7)
|
|
191
|
+
expected_end = _local_boundary(next_end_day, local_zone).astimezone(timezone.utc)
|
|
192
|
+
if r["starts_at"] != prior_end.isoformat() or r["ends_at"] != expected_end.isoformat():
|
|
193
|
+
raise CadenceInputError("Persisted future cycle conflicts with the cadence.")
|
|
194
|
+
intervals.append((prior_end, expected_end))
|
|
195
|
+
timestamp = now_iso()
|
|
196
|
+
for idx, (begin, end) in enumerate(intervals, start=1):
|
|
197
|
+
key = begin.isoformat()
|
|
198
|
+
if idx <= len(persisted):
|
|
199
|
+
existing = persisted[idx - 1]
|
|
200
|
+
if existing["number"] != idx or existing["cadence_boundary_at"] != key or existing["ends_at"] != end.isoformat():
|
|
201
|
+
raise CadenceInputError("Cycle schedule conflicts with persisted intervals.")
|
|
202
|
+
else:
|
|
203
|
+
conn.execute(cycle.insert().values(id=new_id(), organization_id=org_id,
|
|
204
|
+
team_id=team_id, number=idx, name=f"Cycle {idx}",
|
|
205
|
+
starts_at=key, ends_at=end.isoformat(), cadence_boundary_at=key,
|
|
206
|
+
progress=0, created_at=timestamp, updated_at=timestamp))
|
|
207
|
+
active_number = None if before_start else next(i for i, (begin, end) in enumerate(intervals, 1) if begin <= current < end)
|
|
208
|
+
active = (conn.execute(select(cycle).where(and_(cycle.c.team_id == team_id,
|
|
209
|
+
cycle.c.number == active_number))).mappings().one() if active_number else None)
|
|
210
|
+
if active:
|
|
211
|
+
newly_completed = []
|
|
212
|
+
for past in persisted:
|
|
213
|
+
if past["number"] < active_number and not past["completed_at"]:
|
|
214
|
+
conn.execute(cycle.update().where(cycle.c.id == past["id"]).values(completed_at=past["ends_at"], updated_at=timestamp))
|
|
215
|
+
newly_completed.append(past["id"])
|
|
216
|
+
if newly_completed:
|
|
217
|
+
# Linear-style rollover: unfinished issues follow the active pointer.
|
|
218
|
+
_rollover_cycle_issues(conn, org_id, team_id, newly_completed, active["id"], timestamp)
|
|
219
|
+
if row.get("active_cycle_id") != (active["id"] if active else None):
|
|
220
|
+
conn.execute(team.update().where(and_(team.c.organization_id == org_id,
|
|
221
|
+
team.c.id == team_id)).values(active_cycle_id=active["id"] if active else None, updated_at=timestamp))
|
|
222
|
+
upcoming = conn.execute(select(cycle).where(and_(cycle.c.organization_id == org_id,
|
|
223
|
+
cycle.c.team_id == team_id, cycle.c.number > (active_number or 0))).order_by(cycle.c.number).limit(2)).mappings().all()
|
|
224
|
+
def serialize(r):
|
|
225
|
+
return {"id": r["id"], "name": r["name"], "number": r["number"],
|
|
226
|
+
"startsAt": r["starts_at"], "endsAt": r["ends_at"],
|
|
227
|
+
"completedAt": r["completed_at"], "progress": r["progress"],
|
|
228
|
+
"_team_id": team_id}
|
|
229
|
+
return {"enabled": True, "weekday": weekday, "timezone": zone_name,
|
|
230
|
+
"policyVersion": POLICY_VERSION, "activeCycle": serialize(active) if active else None,
|
|
231
|
+
"upcomingCycles": [serialize(r) for r in upcoming]}
|
hoja_server/cli.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""`hoja-serve` entry point.
|
|
2
|
+
|
|
3
|
+
Subcommands:
|
|
4
|
+
serve Start the GraphQL backend.
|
|
5
|
+
seed Create an organization, user, team, states, and token.
|
|
6
|
+
token Mint a token for an existing organization user.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
from sqlalchemy.exc import IntegrityError
|
|
14
|
+
|
|
15
|
+
from hoja_server import __version__
|
|
16
|
+
from hoja_server.db import (
|
|
17
|
+
api_key,
|
|
18
|
+
display_database_target,
|
|
19
|
+
gen_token,
|
|
20
|
+
make_engine,
|
|
21
|
+
migrate,
|
|
22
|
+
new_id,
|
|
23
|
+
now_iso,
|
|
24
|
+
resolve_database_target,
|
|
25
|
+
resolve_token_identity,
|
|
26
|
+
seed_tenant,
|
|
27
|
+
token_hash,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _database_target(args) -> str:
|
|
32
|
+
return resolve_database_target(
|
|
33
|
+
database_url=args.database_url,
|
|
34
|
+
db_path=args.db,
|
|
35
|
+
tenant=args.tenant,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _worker_app():
|
|
40
|
+
"""uvicorn factory for --workers > 1 (each worker process builds its own app)."""
|
|
41
|
+
import os
|
|
42
|
+
|
|
43
|
+
from hoja_server.app import create_app
|
|
44
|
+
return create_app(database_url=os.environ["HOJA_SERVE_TARGET"],
|
|
45
|
+
open_mode=os.environ.get("HOJA_SERVE_OPEN") == "1")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _cmd_serve(args):
|
|
49
|
+
import os
|
|
50
|
+
|
|
51
|
+
import uvicorn
|
|
52
|
+
|
|
53
|
+
from hoja_server.app import create_app
|
|
54
|
+
target = _database_target(args)
|
|
55
|
+
print(f"hoja-serve v{__version__}")
|
|
56
|
+
print(f" tenant : {args.tenant}")
|
|
57
|
+
print(f" db : {display_database_target(target)}")
|
|
58
|
+
print(f" url : http://{args.host}:{args.port}/graphql")
|
|
59
|
+
print(f" open : {args.open}")
|
|
60
|
+
options = {"host": args.host, "port": args.port, "log_level": args.log_level,
|
|
61
|
+
"ws_per_message_deflate": args.ws_deflate, "backlog": 4096}
|
|
62
|
+
if args.workers > 1:
|
|
63
|
+
# Realtime fan-out is per process; workers share change events through the
|
|
64
|
+
# database (PostgreSQL LISTEN/NOTIFY, or polling the SQLite change log).
|
|
65
|
+
print(f" workers: {args.workers}")
|
|
66
|
+
os.environ["HOJA_SERVE_TARGET"] = target
|
|
67
|
+
os.environ["HOJA_SERVE_OPEN"] = "1" if args.open else "0"
|
|
68
|
+
uvicorn.run("hoja_server.cli:_worker_app", factory=True, workers=args.workers, **options)
|
|
69
|
+
return
|
|
70
|
+
uvicorn.run(create_app(database_url=target, open_mode=args.open), **options)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _cmd_migrate(args):
|
|
74
|
+
target = _database_target(args)
|
|
75
|
+
engine = make_engine(target)
|
|
76
|
+
try:
|
|
77
|
+
migrate(engine)
|
|
78
|
+
except (RuntimeError, IntegrityError) as exc:
|
|
79
|
+
print(f"Migration failed: {exc}", file=sys.stderr)
|
|
80
|
+
raise SystemExit(1) from exc
|
|
81
|
+
finally:
|
|
82
|
+
engine.dispose()
|
|
83
|
+
print(f"Migrated database at {display_database_target(target)}")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _cmd_seed(args):
|
|
87
|
+
target = _database_target(args)
|
|
88
|
+
engine = make_engine(target)
|
|
89
|
+
migrate(engine)
|
|
90
|
+
try:
|
|
91
|
+
info = seed_tenant(
|
|
92
|
+
engine, org_name=args.org, org_url_key=args.org_key,
|
|
93
|
+
team_key=args.team_key, team_name=args.team_name,
|
|
94
|
+
user_name=args.user, user_email=args.email,
|
|
95
|
+
token=args.token, demo_issues=not args.no_demo,
|
|
96
|
+
)
|
|
97
|
+
except ValueError as exc:
|
|
98
|
+
print(f"Seed failed: {exc}", file=sys.stderr)
|
|
99
|
+
raise SystemExit(1) from exc
|
|
100
|
+
print(f"Seeded tenant '{args.tenant}' at {display_database_target(target)}")
|
|
101
|
+
print(f" org : {args.org}")
|
|
102
|
+
print(f" team : {info['team_key']}")
|
|
103
|
+
print(f" user : {args.user} <{args.email}>")
|
|
104
|
+
print(f" TOKEN : {info['token']}")
|
|
105
|
+
print()
|
|
106
|
+
print("Use it with hoja:")
|
|
107
|
+
print(f" export HOJA_TOKEN='{info['token']}'")
|
|
108
|
+
print(f" hoja --token '{info['token']}' me # (after wiring base_url)")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _cmd_token(args):
|
|
112
|
+
target = _database_target(args)
|
|
113
|
+
engine = make_engine(target)
|
|
114
|
+
try:
|
|
115
|
+
user_id, org_id = resolve_token_identity(
|
|
116
|
+
engine,
|
|
117
|
+
organization_ref=args.organization,
|
|
118
|
+
user_ref=args.user,
|
|
119
|
+
email=args.email,
|
|
120
|
+
)
|
|
121
|
+
except ValueError as exc:
|
|
122
|
+
print(f"Token creation failed: {exc}", file=sys.stderr)
|
|
123
|
+
raise SystemExit(1) from exc
|
|
124
|
+
try:
|
|
125
|
+
with engine.begin() as conn:
|
|
126
|
+
tok = args.token or gen_token()
|
|
127
|
+
conn.execute(api_key.insert().values(
|
|
128
|
+
id=new_id(), token_hash=token_hash(tok), label=args.label,
|
|
129
|
+
user_id=user_id, organization_id=org_id, created_at=now_iso()))
|
|
130
|
+
except IntegrityError as exc:
|
|
131
|
+
print("Token creation failed: API token already exists.", file=sys.stderr)
|
|
132
|
+
raise SystemExit(1) from exc
|
|
133
|
+
print(tok)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def main(argv=None):
|
|
137
|
+
p = argparse.ArgumentParser(prog="hoja-serve", description="hoja local backend")
|
|
138
|
+
p.add_argument("--version", action="version", version=f"hoja-serve {__version__}")
|
|
139
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
140
|
+
|
|
141
|
+
s = sub.add_parser("serve", help="start the GraphQL server")
|
|
142
|
+
s.add_argument("--tenant", default="default")
|
|
143
|
+
s.add_argument("--database-url", default=None, help="explicit SQLAlchemy database URL")
|
|
144
|
+
s.add_argument("--db", default=None, help="explicit DB path (overrides tenant)")
|
|
145
|
+
s.add_argument("--host", default="127.0.0.1")
|
|
146
|
+
s.add_argument("--port", type=int, default=8787)
|
|
147
|
+
s.add_argument("--open", action="store_true", help="offline open mode: any token → first identity")
|
|
148
|
+
s.add_argument("--log-level", default="warning")
|
|
149
|
+
s.add_argument("--workers", type=int, default=1,
|
|
150
|
+
help="server processes; realtime clients are spread across them")
|
|
151
|
+
s.add_argument("--no-ws-deflate", dest="ws_deflate", action="store_false",
|
|
152
|
+
help="disable WebSocket compression (less CPU per client on large fan-outs)")
|
|
153
|
+
s.set_defaults(func=_cmd_serve)
|
|
154
|
+
|
|
155
|
+
mg = sub.add_parser("migrate", help="apply outstanding database schema revisions")
|
|
156
|
+
mg.add_argument("--tenant", default="default")
|
|
157
|
+
mg.add_argument("--database-url", default=None, help="explicit SQLAlchemy database URL")
|
|
158
|
+
mg.add_argument("--db", default=None)
|
|
159
|
+
mg.set_defaults(func=_cmd_migrate)
|
|
160
|
+
|
|
161
|
+
sd = sub.add_parser("seed", help="seed a tenant DB")
|
|
162
|
+
sd.add_argument("--tenant", default="default")
|
|
163
|
+
sd.add_argument("--database-url", default=None, help="explicit SQLAlchemy database URL")
|
|
164
|
+
sd.add_argument("--db", default=None)
|
|
165
|
+
sd.add_argument("--org", default="Local")
|
|
166
|
+
sd.add_argument("--org-key", default=None, help="unique organization URL key")
|
|
167
|
+
sd.add_argument("--team-key", default="ENG")
|
|
168
|
+
sd.add_argument("--team-name", default="Engineering")
|
|
169
|
+
sd.add_argument("--user", default="Local User")
|
|
170
|
+
sd.add_argument("--email", default="you@local")
|
|
171
|
+
sd.add_argument("--token", default=None, help="use a specific token instead of random")
|
|
172
|
+
sd.add_argument("--no-demo", action="store_true", help="don't create demo issues")
|
|
173
|
+
sd.set_defaults(func=_cmd_seed)
|
|
174
|
+
|
|
175
|
+
t = sub.add_parser("token", help="mint a new token for a tenant")
|
|
176
|
+
t.add_argument("--tenant", default="default")
|
|
177
|
+
t.add_argument("--database-url", default=None, help="explicit SQLAlchemy database URL")
|
|
178
|
+
t.add_argument("--db", default=None)
|
|
179
|
+
t.add_argument("--organization", default=None, help="organization ID or URL key")
|
|
180
|
+
t.add_argument("--user", default=None, help="user ID in the selected organization")
|
|
181
|
+
t.add_argument("--email", default=None, help="user email in the selected organization")
|
|
182
|
+
t.add_argument("--token", default=None)
|
|
183
|
+
t.add_argument("--label", default="cli")
|
|
184
|
+
t.set_defaults(func=_cmd_token)
|
|
185
|
+
|
|
186
|
+
args = p.parse_args(argv)
|
|
187
|
+
args.func(args)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
if __name__ == "__main__":
|
|
191
|
+
main()
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Cloudflare Realtime (SFU + TURN) HTTP client.
|
|
2
|
+
|
|
3
|
+
Media flows browser <-> Cloudflare; this server only signs and authorizes the control calls,
|
|
4
|
+
so the SFU app secret and TURN key never reach a browser.
|
|
5
|
+
|
|
6
|
+
Configuration (environment):
|
|
7
|
+
HOJA_CF_REALTIME_APP_ID, HOJA_CF_REALTIME_APP_SECRET SFU application
|
|
8
|
+
HOJA_CF_TURN_KEY_ID, HOJA_CF_TURN_KEY_API_TOKEN TURN key (optional)
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
SFU_BASE = "https://rtc.live.cloudflare.com/v1"
|
|
18
|
+
ICE_TTL_SECONDS = 3600
|
|
19
|
+
TIMEOUT = httpx.Timeout(10.0, connect=5.0)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SFUError(Exception):
|
|
23
|
+
"""Cloudflare rejected or failed a control call."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, message: str, status: int = 502) -> None:
|
|
26
|
+
super().__init__(message)
|
|
27
|
+
self.status = status
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class CloudflareRealtime:
|
|
31
|
+
def __init__(self, app_id: str, app_secret: str, turn_key_id: str | None = None,
|
|
32
|
+
turn_key_token: str | None = None, base_url: str = SFU_BASE,
|
|
33
|
+
client: httpx.AsyncClient | None = None) -> None:
|
|
34
|
+
self.app_id = app_id
|
|
35
|
+
self._secret = app_secret
|
|
36
|
+
self._turn_id = turn_key_id
|
|
37
|
+
self._turn_token = turn_key_token
|
|
38
|
+
self._base = base_url.rstrip("/")
|
|
39
|
+
self._client = client
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def from_env(cls) -> CloudflareRealtime | None:
|
|
43
|
+
app_id = os.environ.get("HOJA_CF_REALTIME_APP_ID", "").strip()
|
|
44
|
+
secret = os.environ.get("HOJA_CF_REALTIME_APP_SECRET", "").strip()
|
|
45
|
+
if not app_id or not secret:
|
|
46
|
+
return None
|
|
47
|
+
return cls(app_id, secret, os.environ.get("HOJA_CF_TURN_KEY_ID", "").strip() or None,
|
|
48
|
+
os.environ.get("HOJA_CF_TURN_KEY_API_TOKEN", "").strip() or None)
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def turn_configured(self) -> bool:
|
|
52
|
+
return bool(self._turn_id and self._turn_token)
|
|
53
|
+
|
|
54
|
+
def _http(self) -> httpx.AsyncClient:
|
|
55
|
+
if self._client is None:
|
|
56
|
+
self._client = httpx.AsyncClient(timeout=TIMEOUT)
|
|
57
|
+
return self._client
|
|
58
|
+
|
|
59
|
+
async def aclose(self) -> None:
|
|
60
|
+
if self._client is not None:
|
|
61
|
+
await self._client.aclose()
|
|
62
|
+
self._client = None
|
|
63
|
+
|
|
64
|
+
async def _call(self, method: str, url: str, token: str, body: Any = None) -> dict:
|
|
65
|
+
try:
|
|
66
|
+
resp = await self._http().request(
|
|
67
|
+
method, url, headers={"Authorization": f"Bearer {token}"},
|
|
68
|
+
**({"json": body} if body is not None else {}))
|
|
69
|
+
except httpx.HTTPError as exc:
|
|
70
|
+
raise SFUError(f"Realtime service unreachable ({type(exc).__name__}).", 502) from exc
|
|
71
|
+
try:
|
|
72
|
+
data = resp.json()
|
|
73
|
+
except ValueError:
|
|
74
|
+
data = {}
|
|
75
|
+
if resp.status_code >= 400:
|
|
76
|
+
detail = data.get("errorDescription") or data.get("error") or f"HTTP {resp.status_code}"
|
|
77
|
+
raise SFUError(f"Realtime service rejected the request: {detail}",
|
|
78
|
+
429 if resp.status_code == 429 else 502)
|
|
79
|
+
return data if isinstance(data, dict) else {}
|
|
80
|
+
|
|
81
|
+
def _sfu(self, path: str) -> str:
|
|
82
|
+
return f"{self._base}/apps/{self.app_id}{path}"
|
|
83
|
+
|
|
84
|
+
async def new_session(self) -> dict:
|
|
85
|
+
return await self._call("POST", self._sfu("/sessions/new"), self._secret)
|
|
86
|
+
|
|
87
|
+
async def add_tracks(self, session_id: str, body: dict) -> dict:
|
|
88
|
+
return await self._call("POST", self._sfu(f"/sessions/{session_id}/tracks/new"), self._secret, body)
|
|
89
|
+
|
|
90
|
+
async def update_tracks(self, session_id: str, body: dict) -> dict:
|
|
91
|
+
return await self._call("PUT", self._sfu(f"/sessions/{session_id}/tracks/update"), self._secret, body)
|
|
92
|
+
|
|
93
|
+
async def close_tracks(self, session_id: str, body: dict) -> dict:
|
|
94
|
+
return await self._call("PUT", self._sfu(f"/sessions/{session_id}/tracks/close"), self._secret, body)
|
|
95
|
+
|
|
96
|
+
async def renegotiate(self, session_id: str, body: dict) -> dict:
|
|
97
|
+
return await self._call("PUT", self._sfu(f"/sessions/{session_id}/renegotiate"), self._secret, body)
|
|
98
|
+
|
|
99
|
+
async def ice_servers(self, ttl: int = ICE_TTL_SECONDS) -> list[dict]:
|
|
100
|
+
"""Short-lived STUN/TURN credentials; free STUN only when no TURN key is configured."""
|
|
101
|
+
if not self.turn_configured:
|
|
102
|
+
return [{"urls": ["stun:stun.cloudflare.com:3478"]}]
|
|
103
|
+
url = f"{self._base}/turn/keys/{self._turn_id}/credentials/generate-ice-servers"
|
|
104
|
+
data = await self._call("POST", url, self._turn_token or "", {"ttl": ttl})
|
|
105
|
+
servers = data.get("iceServers")
|
|
106
|
+
if isinstance(servers, dict): # older responses wrap a single object
|
|
107
|
+
servers = [servers]
|
|
108
|
+
if not isinstance(servers, list) or not servers:
|
|
109
|
+
raise SFUError("Realtime service returned no ICE servers.")
|
|
110
|
+
return servers
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""ABAC policy for issue comments (see ``abac`` for the evaluation model).
|
|
2
|
+
|
|
3
|
+
Words carry their author's name, so only the author may change them. Admins moderate by
|
|
4
|
+
deleting, never by rewriting: an admin edit would put words in someone else's mouth.
|
|
5
|
+
|
|
6
|
+
subject
|
|
7
|
+
user_id the caller's user id
|
|
8
|
+
admin caller is an active workspace admin
|
|
9
|
+
resource
|
|
10
|
+
author_id the comment's author (None for system/imported comments)
|
|
11
|
+
archived the comment was deleted
|
|
12
|
+
team_visible the caller can see the issue's team (private teams)
|
|
13
|
+
|
|
14
|
+
Matrix (after the visibility/archived denials):
|
|
15
|
+
|
|
16
|
+
caller edit delete
|
|
17
|
+
author yes yes
|
|
18
|
+
workspace admin no yes
|
|
19
|
+
other member no no
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from sqlalchemy import and_, select
|
|
24
|
+
|
|
25
|
+
from hoja_server.abac import Decision, Policy, deny, permit
|
|
26
|
+
from hoja_server.db import user
|
|
27
|
+
from hoja_server.store import team_visible
|
|
28
|
+
|
|
29
|
+
EDIT = "comment.edit"
|
|
30
|
+
DELETE = "comment.delete"
|
|
31
|
+
|
|
32
|
+
# Denials that must look exactly like "no such comment" so existence never leaks.
|
|
33
|
+
NOT_FOUND_RULES = frozenset({"d-hidden", "d-archived"})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _is_author(c) -> bool:
|
|
37
|
+
return bool(c.r.author_id) and c.r.author_id == c.s.user_id
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
RULES = [
|
|
41
|
+
deny("d-hidden", {EDIT, DELETE}, lambda c: not c.r.team_visible, "Comment not found."),
|
|
42
|
+
deny("d-archived", {EDIT, DELETE}, lambda c: bool(c.r.archived), "Comment not found."),
|
|
43
|
+
permit("p-author", {EDIT, DELETE}, _is_author, "Authors manage their own comments."),
|
|
44
|
+
permit("p-admin-moderate", DELETE, lambda c: bool(c.s.admin), "Workspace admins can remove any comment."),
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
POLICY = Policy(RULES)
|
|
48
|
+
|
|
49
|
+
DENIED_MESSAGE = {
|
|
50
|
+
EDIT: "Only the comment's author can edit it.",
|
|
51
|
+
DELETE: "Only the comment's author or a workspace admin can delete it.",
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def decide(action: str, subject: dict, resource: dict) -> Decision:
|
|
56
|
+
return POLICY.decide(action, subject, resource)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def subject(conn, org_id: str, viewer_id: str | None) -> dict:
|
|
60
|
+
admin = conn.execute(select(user.c.admin).where(and_(
|
|
61
|
+
user.c.id == viewer_id, user.c.organization_id == org_id,
|
|
62
|
+
user.c.active.is_(True), user.c.archived_at.is_(None),
|
|
63
|
+
))).scalar() if viewer_id else None
|
|
64
|
+
return {"user_id": viewer_id, "admin": bool(admin)}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def resource(conn, org_id: str, viewer_id: str | None, *, author_id: str | None,
|
|
68
|
+
archived: bool, team_id: str | None) -> dict:
|
|
69
|
+
visible = bool(viewer_id) and (not team_id or team_visible(conn, org_id, viewer_id, team_id))
|
|
70
|
+
return {"author_id": author_id, "archived": archived, "team_visible": visible}
|