ai_co_discuss 0.4.63 → 0.4.64
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.
- package/backend/external_members.py +529 -0
- package/backend/free_room.py +66 -14
- package/backend/schema.sql +46 -0
- package/backend/server.py +40 -1
- package/frontend/locales/en/backend.json +38 -1
- package/frontend/locales/en/external.json +162 -0
- package/package.json +1 -1
- package/runner/adapters/api.mjs +66 -7
- package/runner/adapters/claude.mjs +33 -3
- package/runner/adapters/index.mjs +12 -4
- package/runner/adapters/profiles.mjs +28 -6
- package/runner/codiscuss.mjs +11 -2
- package/runner/device_auth.mjs +9 -5
- package/runner/discuss.py +82 -3
- package/runner/discussion_launch.mjs +9 -0
- package/runner/discussion_service.mjs +2 -0
- package/runner/expert_prompts.mjs +17 -1
- package/runner/external_client.mjs +885 -0
- package/runner/external_gateway.mjs +454 -0
- package/runner/i18n_en.mjs +107 -2
- package/runner/relay_channel.mjs +13 -0
- package/runner/remote_launch.mjs +18 -9
- package/runner/remote_policy.mjs +14 -0
- package/runner/repo_read.mjs +349 -0
- package/web/admin.js +1 -1
- package/web/backup.js +1 -1
- package/web/i18n.js +1 -1
- package/web/join.html +106 -0
- package/web/modern.css +1 -1
- package/web/modern.js +54 -54
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
"""External members: AIs that run on another computer and reach this room only through the runner's gateway.
|
|
2
|
+
|
|
3
|
+
An external member is a `room_members` row with `access='external'` plus one `external_members` row holding where it
|
|
4
|
+
runs, what it may read, until when, and its read quota. This module is the room-side authority (DESIGN D4): it decides
|
|
5
|
+
validity, expiry and revocation, keeps the read audit and quota counts, and serves the only routes an external
|
|
6
|
+
credential may use (`/api/external/rooms/{room}/...`). Every other route refuses an external credential or a request
|
|
7
|
+
the gateway marked as external; see `guard_route`. Contract: .dev/plans/远程协作与多人房间/子Task1_B侧后端/CONTRACT.md.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import posixpath
|
|
13
|
+
import time
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
|
|
16
|
+
from . import free_room
|
|
17
|
+
from .identity import MAX_ROOM_AGENTS, is_ai
|
|
18
|
+
from .runtime import begin_write, require_owner, token_hash
|
|
19
|
+
from .texts import Text, text_payload
|
|
20
|
+
|
|
21
|
+
EXTERNAL_HEADER = "X-CoDiscuss-External"
|
|
22
|
+
BRIDGE_HEADER = "X-CoDiscuss-Bridge"
|
|
23
|
+
EXTERNAL_PREFIX = ["api", "external", "rooms"]
|
|
24
|
+
SCOPES = ("discuss", "read")
|
|
25
|
+
QUOTA_KEYS = ("hourly_bytes", "total_bytes", "hourly_reads")
|
|
26
|
+
DEFAULT_QUOTA = {"hourly_bytes": 4 * 1024 * 1024, "total_bytes": 64 * 1024 * 1024, "hourly_reads": 600}
|
|
27
|
+
MAX_QUOTA = {"hourly_bytes": 1024 ** 3, "total_bytes": 100 * 1024 ** 3, "hourly_reads": 100000}
|
|
28
|
+
MAX_EXTERNAL_SECONDS = 365 * 86400
|
|
29
|
+
MAX_DIRECTORIES = 20
|
|
30
|
+
MAX_DIRECTORY_LENGTH = 500
|
|
31
|
+
MAX_MACHINE = 200
|
|
32
|
+
MAX_MACHINE_LABEL = 80
|
|
33
|
+
MAX_ADAPTER = 40
|
|
34
|
+
HOUR_SECONDS = 3600
|
|
35
|
+
READ_OPS = ("ls", "read", "grep")
|
|
36
|
+
READ_OUTCOMES = ("ok", "denied")
|
|
37
|
+
MAX_READ_PATH = 1000
|
|
38
|
+
MAX_READ_BYTES = 64 * 1024 * 1024
|
|
39
|
+
MAX_READ_REASON = 300
|
|
40
|
+
READ_PAGE = 100
|
|
41
|
+
MAX_READ_PAGE = 500
|
|
42
|
+
END_REASONS = ("revoked", "expired", "left")
|
|
43
|
+
DECLINE_OUTCOMES = ("declined", "timeout")
|
|
44
|
+
MAX_DECLINES = 100
|
|
45
|
+
EXECUTION_ACTIONS = ("renew", "segments", "delivery", "fail", "release", "quiet")
|
|
46
|
+
MESSAGE_PARAMS = ("after", "limit", "page", "q", "author", "mention", "execution_id", "request_id", "max_output_chars")
|
|
47
|
+
ANSWER_FIELDS = ("text", "text_text", "execution_id", "submission_id", "reply_to")
|
|
48
|
+
ENDED_TEXTS = {"revoked": Text("外部成员已被撤销"), "expired": Text("外部成员已到期"), "left": Text("外部成员已退出")}
|
|
49
|
+
EXTERNAL_SQL = """SELECT m.id,m.room_id,m.name,m.adapter,m.role,m.status,m.access,m.session_mode,m.read_until,m.token_hash,
|
|
50
|
+
x.machine,x.machine_label,x.scope,x.directories,x.expires_at,x.hourly_bytes,x.total_bytes,x.hourly_reads,
|
|
51
|
+
x.created_at,x.updated_at,x.ended_at,x.end_reason
|
|
52
|
+
FROM external_members x JOIN room_members m ON m.id=x.member_id"""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def classified(error_class, message, code, **details):
|
|
56
|
+
"""Build an error whose response body carries a machine-readable `code` beside the message."""
|
|
57
|
+
error = error_class(message)
|
|
58
|
+
error.details = {"code": code, **details}
|
|
59
|
+
return error
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def is_external_path(parts):
|
|
63
|
+
"""Whether a split URL path is one of the member-scope routes for external members."""
|
|
64
|
+
return parts[:3] == EXTERNAL_PREFIX and len(parts) >= 5
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def guard_route(connect, headers, parts):
|
|
68
|
+
"""Refuse every route outside `/api/external/` for a request marked external or carrying an external credential.
|
|
69
|
+
|
|
70
|
+
Runs before the device bridge and all routing, because the local site treats a credential-less loopback request as
|
|
71
|
+
the administrator: the gateway's marker header, not the credential alone, is what keeps such a request out.
|
|
72
|
+
"""
|
|
73
|
+
marked = headers.get(EXTERNAL_HEADER) is not None
|
|
74
|
+
if marked and headers.get(BRIDGE_HEADER) is not None:
|
|
75
|
+
raise classified(PermissionError, Text("外部成员请求不能经设备中转"), "external_route_forbidden")
|
|
76
|
+
if parts[:3] == EXTERNAL_PREFIX:
|
|
77
|
+
return
|
|
78
|
+
hashed = token_hash(headers.get("X-Discussion-Token", ""))
|
|
79
|
+
if not marked and hashed:
|
|
80
|
+
connection = connect()
|
|
81
|
+
try:
|
|
82
|
+
marked = connection.execute("SELECT 1 FROM external_members WHERE token_hash=?", (hashed,)).fetchone() is not None
|
|
83
|
+
finally:
|
|
84
|
+
connection.close()
|
|
85
|
+
if marked:
|
|
86
|
+
raise classified(PermissionError, Text("外部成员只能使用成员范围接口"), "external_route_forbidden")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def quota_of(row):
|
|
90
|
+
"""The member's three quota limits."""
|
|
91
|
+
return {key: row[key] for key in QUOTA_KEYS}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def usage_of(connection, member_id, now=None):
|
|
95
|
+
"""Read counts from the persisted audit: allowed bytes and reads in the last hour, allowed bytes in total, denials."""
|
|
96
|
+
since = ((now or int(time.time())) - HOUR_SECONDS) * 1000
|
|
97
|
+
row = connection.execute("""SELECT COALESCE(SUM(CASE WHEN allowed=1 AND at>? THEN bytes END),0),
|
|
98
|
+
COALESCE(SUM(CASE WHEN allowed=1 AND at>? THEN 1 END),0),COALESCE(SUM(CASE WHEN allowed=1 THEN bytes END),0),
|
|
99
|
+
COALESCE(SUM(CASE WHEN allowed=0 THEN 1 END),0) FROM external_reads WHERE member_id=?""", (since, since, member_id)).fetchone()
|
|
100
|
+
return {"hour_bytes": row[0], "hour_reads": row[1], "total_bytes": row[2], "denied": row[3]}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def directory_names(directories):
|
|
104
|
+
"""Directory roots by number with only their last segment, for views that must not show local paths."""
|
|
105
|
+
return [{"root": index, "name": posixpath.basename(path.replace("\\", "/").rstrip("/")) or path}
|
|
106
|
+
for index, path in enumerate(directories)]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def owner_view(connection, row):
|
|
110
|
+
"""Describe one external member for the owner, with full directory paths and current usage."""
|
|
111
|
+
labels = free_room.member_display_names(connection, row["room_id"])
|
|
112
|
+
return {"member_id": row["id"], "name": row["name"], "label": labels.get(row["name"], row["name"]), "adapter": row["adapter"],
|
|
113
|
+
"status": row["status"], "machine": row["machine"], "machine_label": row["machine_label"], "scope": row["scope"],
|
|
114
|
+
"directories": json.loads(row["directories"]), "expires_at": row["expires_at"], "quota": quota_of(row),
|
|
115
|
+
"usage": usage_of(connection, row["id"]), "created_at": row["created_at"], "updated_at": row["updated_at"],
|
|
116
|
+
"ended_at": row["ended_at"], "end_reason": row["end_reason"]}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def room_view_field(connection, member_id):
|
|
120
|
+
"""The `external` field of a member in the room view, or None for a local member; no local paths."""
|
|
121
|
+
row = connection.execute("SELECT scope,expires_at,machine_label,directories FROM external_members WHERE member_id=?",
|
|
122
|
+
(member_id,)).fetchone()
|
|
123
|
+
if not row:
|
|
124
|
+
return None
|
|
125
|
+
return {"scope": row["scope"], "expires_at": row["expires_at"], "machine_label": row["machine_label"],
|
|
126
|
+
"directories": directory_names(json.loads(row["directories"]))}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def external_row(connection, room_id, member_id):
|
|
130
|
+
"""One external member of a room, or LookupError."""
|
|
131
|
+
row = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? AND x.member_id=?", (room_id, member_id)).fetchone()
|
|
132
|
+
if not row:
|
|
133
|
+
raise LookupError(Text("外部成员不存在"))
|
|
134
|
+
return row
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def end_member(connection, row, reason):
|
|
138
|
+
"""End an external member: void its live work, cancel its open requests, and refuse its credential from now on."""
|
|
139
|
+
now = int(time.time())
|
|
140
|
+
free_room.discussion.session_member_change(connection, row["room_id"], row, "remove")
|
|
141
|
+
free_room.stop_member_work(connection, row["id"], ENDED_TEXTS[reason], "member_removed")
|
|
142
|
+
connection.execute("UPDATE room_members SET status='removed',role='member' WHERE id=?", (row["id"],))
|
|
143
|
+
connection.execute("UPDATE external_members SET ended_at=?,end_reason=?,updated_at=? WHERE member_id=? AND ended_at=0",
|
|
144
|
+
(now, reason, now, row["id"]))
|
|
145
|
+
free_room.settle_batches(connection, row["room_id"])
|
|
146
|
+
free_room.sync_participants(connection, row["room_id"])
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def expire_room(connection, room_id):
|
|
150
|
+
"""End every external member of the room whose time is up; returns whether any ended."""
|
|
151
|
+
rows = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? AND m.status='active' AND x.ended_at=0 AND x.expires_at<=?",
|
|
152
|
+
(room_id, int(time.time()))).fetchall()
|
|
153
|
+
for row in rows:
|
|
154
|
+
end_member(connection, row, "expired")
|
|
155
|
+
return bool(rows)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def roster_revision(connection, room_id):
|
|
159
|
+
"""Version of the room's roster and external settings that a new external member is checked against (red line 1)."""
|
|
160
|
+
members = connection.execute("SELECT id,name,status,access FROM room_members WHERE room_id=? ORDER BY id", (room_id,)).fetchall()
|
|
161
|
+
externals = connection.execute("""SELECT member_id,scope,directories,expires_at,hourly_bytes,total_bytes,hourly_reads,ended_at
|
|
162
|
+
FROM external_members WHERE room_id=? ORDER BY member_id""", (room_id,)).fetchall()
|
|
163
|
+
state = json.dumps([[list(row) for row in members], [list(row) for row in externals]], ensure_ascii=False)
|
|
164
|
+
return hashlib.sha256(state.encode()).hexdigest()
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def checked_scope(scope, directories):
|
|
168
|
+
"""Validate the opening level and directories together; reading needs at least one directory, discussion none."""
|
|
169
|
+
if scope not in SCOPES:
|
|
170
|
+
raise ValueError(Text("scope 须为 discuss 或 read"))
|
|
171
|
+
if not isinstance(directories, list) or len(directories) > MAX_DIRECTORIES or any(
|
|
172
|
+
not isinstance(item, str) or not item.strip() or len(item) > MAX_DIRECTORY_LENGTH for item in directories):
|
|
173
|
+
raise ValueError(Text("directories 须为最多 {count} 个目录,每个不超过 {length} 字", count=MAX_DIRECTORIES, length=MAX_DIRECTORY_LENGTH))
|
|
174
|
+
if len(set(directories)) != len(directories):
|
|
175
|
+
raise ValueError(Text("开放目录不能重复"))
|
|
176
|
+
if scope == "read" and not directories:
|
|
177
|
+
raise ValueError(Text("只读项目须至少开放一个目录"))
|
|
178
|
+
if scope == "discuss" and directories:
|
|
179
|
+
raise ValueError(Text("只讨论时不开放目录"))
|
|
180
|
+
return directories
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def checked_expiry(value, now):
|
|
184
|
+
"""Validate an expiry in epoch seconds: later than now and within the longest allowed span."""
|
|
185
|
+
if type(value) is not int or not now < value <= now + MAX_EXTERNAL_SECONDS:
|
|
186
|
+
raise ValueError(Text("expires_at 须为晚于现在、不超过 {days} 天的秒级时间", days=MAX_EXTERNAL_SECONDS // 86400))
|
|
187
|
+
return value
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def checked_quota(value, current):
|
|
191
|
+
"""Merge given quota limits over `current`; each is a positive integer within its maximum."""
|
|
192
|
+
if value is None:
|
|
193
|
+
return dict(current)
|
|
194
|
+
if not isinstance(value, dict) or set(value) - set(QUOTA_KEYS):
|
|
195
|
+
raise ValueError(Text("quota 只能包含 hourly_bytes、total_bytes、hourly_reads"))
|
|
196
|
+
merged = dict(current)
|
|
197
|
+
for key, item in value.items():
|
|
198
|
+
if type(item) is not int or not 0 < item <= MAX_QUOTA[key]:
|
|
199
|
+
raise ValueError(Text("配额 {key} 须为 1–{limit} 的整数", key=key, limit=MAX_QUOTA[key]))
|
|
200
|
+
merged[key] = item
|
|
201
|
+
return merged
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def checked_text(value, limit, field, required=False):
|
|
205
|
+
"""Validate a bounded single-line text field."""
|
|
206
|
+
if value is None and not required:
|
|
207
|
+
return ""
|
|
208
|
+
if not isinstance(value, str) or (required and not value.strip()) or len(value) > limit:
|
|
209
|
+
raise ValueError(Text("{field} 须为不超过 {limit} 字的文本", field=field, limit=limit))
|
|
210
|
+
return value
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def list_external(connection, room_id, token):
|
|
214
|
+
"""The owner's read entry before adding an external member: every external member and the roster revision."""
|
|
215
|
+
require_owner(connection, room_id, token)
|
|
216
|
+
begin_write(connection)
|
|
217
|
+
expire_room(connection, room_id)
|
|
218
|
+
rows = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? ORDER BY m.id", (room_id,)).fetchall()
|
|
219
|
+
return {"revision": roster_revision(connection, room_id), "members": [owner_view(connection, row) for row in rows]}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def get_external(connection, room_id, member_id, token):
|
|
223
|
+
"""One external member for the owner or the gateway, expired ones ended first."""
|
|
224
|
+
require_owner(connection, room_id, token)
|
|
225
|
+
begin_write(connection)
|
|
226
|
+
expire_room(connection, room_id)
|
|
227
|
+
return owner_view(connection, external_row(connection, room_id, member_id))
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def create_external(connection, room_id, token, payload, now):
|
|
231
|
+
"""Add an external member on redemption; the owner credential and a fresh roster revision are required.
|
|
232
|
+
|
|
233
|
+
Returns:
|
|
234
|
+
(body, status): 201 for a new member, 200 when the same redemption is repeated.
|
|
235
|
+
"""
|
|
236
|
+
require_owner(connection, room_id, token)
|
|
237
|
+
begin_write(connection)
|
|
238
|
+
expire_room(connection, room_id)
|
|
239
|
+
name, member_token = payload.get("name"), payload.get("token")
|
|
240
|
+
machine = checked_text(payload.get("machine"), MAX_MACHINE, "machine", required=True)
|
|
241
|
+
hashed = token_hash(member_token)
|
|
242
|
+
repeated = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? AND m.name=? AND x.token_hash=? AND x.machine=? AND m.status='active'",
|
|
243
|
+
(room_id, name, hashed, machine)).fetchone() if hashed else None
|
|
244
|
+
if repeated:
|
|
245
|
+
return {"member": owner_view(connection, repeated), "revision": roster_revision(connection, room_id)}, 200
|
|
246
|
+
if not isinstance(payload.get("revision"), str) or not payload["revision"]:
|
|
247
|
+
raise ValueError(Text("建立外部成员须先读取外部成员名单,并带上其中的 revision"))
|
|
248
|
+
if payload["revision"] != roster_revision(connection, room_id):
|
|
249
|
+
raise classified(FileExistsError, Text("房间成员已变化,请重新读取外部成员名单后再提交"), "stale_revision")
|
|
250
|
+
if not is_ai(name):
|
|
251
|
+
raise ValueError(Text("成员须为有效 AI 身份"))
|
|
252
|
+
if not hashed:
|
|
253
|
+
raise ValueError(Text("每位成员须提供 32–256 字符的成员凭证"))
|
|
254
|
+
adapter = checked_text(payload.get("adapter", ""), MAX_ADAPTER, "adapter")
|
|
255
|
+
label = checked_text(payload.get("machine_label"), MAX_MACHINE_LABEL, "machine_label")
|
|
256
|
+
directories = checked_scope(payload.get("scope"), payload.get("directories", []))
|
|
257
|
+
expires_at = checked_expiry(payload.get("expires_at"), now)
|
|
258
|
+
quota = checked_quota(payload.get("quota"), DEFAULT_QUOTA)
|
|
259
|
+
if connection.execute("SELECT 1 FROM room_members WHERE room_id=? AND name=? AND status<>'removed'", (room_id, name)).fetchone():
|
|
260
|
+
raise FileExistsError(Text("{name} 已是本房间成员", name=name))
|
|
261
|
+
if connection.execute("SELECT COUNT(*) FROM room_members WHERE room_id=? AND status<>'removed'", (room_id,)).fetchone()[0] >= MAX_ROOM_AGENTS:
|
|
262
|
+
raise FileExistsError(Text("房间成员已满"))
|
|
263
|
+
free_room.require_fresh_member_token(connection, room_id, member_token)
|
|
264
|
+
cursor = connection.execute("""INSERT INTO room_members (room_id,name,adapter,token_hash,access,session_mode,created_at)
|
|
265
|
+
VALUES (?,?,?,?,'external','new',?)""", (room_id, name, adapter, hashed, free_room_now()))
|
|
266
|
+
connection.execute("""INSERT INTO external_members (member_id,room_id,token_hash,machine,machine_label,scope,directories,expires_at,
|
|
267
|
+
hourly_bytes,total_bytes,hourly_reads,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
|
268
|
+
(cursor.lastrowid, room_id, hashed, machine, label, payload["scope"], json.dumps(directories, ensure_ascii=False),
|
|
269
|
+
expires_at, quota["hourly_bytes"], quota["total_bytes"], quota["hourly_reads"], now, now))
|
|
270
|
+
free_room.queue_invited_expert(connection, room_id, name, now)
|
|
271
|
+
free_room.sync_participants(connection, room_id)
|
|
272
|
+
row = external_row(connection, room_id, cursor.lastrowid)
|
|
273
|
+
return {"member": owner_view(connection, row), "revision": roster_revision(connection, room_id)}, 201
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def free_room_now():
|
|
277
|
+
"""The member creation time in the same ISO form other members use (server.utc_now)."""
|
|
278
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def update_external(connection, room_id, member_id, token, payload, now):
|
|
282
|
+
"""The owner adjusts or revokes one external member; bound to that member, so no roster revision (red line 1 exception)."""
|
|
283
|
+
require_owner(connection, room_id, token)
|
|
284
|
+
begin_write(connection)
|
|
285
|
+
expire_room(connection, room_id)
|
|
286
|
+
row = external_row(connection, room_id, member_id)
|
|
287
|
+
action = payload.get("action")
|
|
288
|
+
if action == "revoke":
|
|
289
|
+
if row["status"] == "active":
|
|
290
|
+
end_member(connection, row, "revoked")
|
|
291
|
+
return owner_view(connection, external_row(connection, room_id, member_id))
|
|
292
|
+
if action != "update":
|
|
293
|
+
raise ValueError(Text("action 须为 update 或 revoke"))
|
|
294
|
+
if row["status"] != "active":
|
|
295
|
+
raise classified(FileExistsError, Text("外部成员已结束,不能再调整;需要时重新邀请"), "external_ended", reason=row["end_reason"])
|
|
296
|
+
scope = payload.get("scope", row["scope"])
|
|
297
|
+
directories = payload.get("directories", [] if scope == "discuss" and "directories" not in payload else json.loads(row["directories"]))
|
|
298
|
+
directories = checked_scope(scope, directories)
|
|
299
|
+
expires_at = checked_expiry(payload["expires_at"], now) if "expires_at" in payload else row["expires_at"]
|
|
300
|
+
quota = checked_quota(payload.get("quota"), quota_of(row))
|
|
301
|
+
label = checked_text(payload["machine_label"], MAX_MACHINE_LABEL, "machine_label") if "machine_label" in payload else row["machine_label"]
|
|
302
|
+
connection.execute("""UPDATE external_members SET scope=?,directories=?,expires_at=?,hourly_bytes=?,total_bytes=?,hourly_reads=?,
|
|
303
|
+
machine_label=?,updated_at=? WHERE member_id=?""", (scope, json.dumps(directories, ensure_ascii=False), expires_at,
|
|
304
|
+
quota["hourly_bytes"], quota["total_bytes"], quota["hourly_reads"], label, now, member_id))
|
|
305
|
+
return owner_view(connection, external_row(connection, room_id, member_id))
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def list_reads(connection, room_id, member_id, token, params):
|
|
309
|
+
"""The owner reads one external member's read records in order."""
|
|
310
|
+
require_owner(connection, room_id, token)
|
|
311
|
+
external_row(connection, room_id, member_id)
|
|
312
|
+
after = int(params.get("after", 0) or 0)
|
|
313
|
+
limit = min(MAX_READ_PAGE, max(1, int(params.get("limit", READ_PAGE) or READ_PAGE)))
|
|
314
|
+
rows = connection.execute("""SELECT id,at,op,root,directory,path,bytes,allowed,code,reason FROM external_reads
|
|
315
|
+
WHERE member_id=? AND id>? ORDER BY id LIMIT ?""", (member_id, after, limit + 1)).fetchall()
|
|
316
|
+
reads = [{**dict(row), "allowed": bool(row["allowed"])} for row in rows[:limit]]
|
|
317
|
+
return {"reads": reads, "next_after": reads[-1]["id"] if reads else after, "has_more": len(rows) > limit}
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def checked_read(payload):
|
|
321
|
+
"""Validate one read report from the gateway."""
|
|
322
|
+
op, root, path, size = payload.get("op"), payload.get("root"), payload.get("path", ""), payload.get("bytes")
|
|
323
|
+
outcome, reason = payload.get("outcome"), payload.get("reason", "")
|
|
324
|
+
if op not in READ_OPS or outcome not in READ_OUTCOMES:
|
|
325
|
+
raise ValueError(Text("op 须为 ls、read 或 grep,outcome 须为 ok 或 denied"))
|
|
326
|
+
if type(root) is not int or root < 0 or not isinstance(path, str) or len(path) > MAX_READ_PATH:
|
|
327
|
+
raise ValueError(Text("root 须为非负整数,path 不超过 {limit} 字", limit=MAX_READ_PATH))
|
|
328
|
+
if type(size) is not int or not 0 <= size <= MAX_READ_BYTES:
|
|
329
|
+
raise ValueError(Text("bytes 须为 0–{limit} 的整数", limit=MAX_READ_BYTES))
|
|
330
|
+
if not isinstance(reason, str) or len(reason) > MAX_READ_REASON or (outcome == "denied" and not reason.strip()):
|
|
331
|
+
raise ValueError(Text("reason 不超过 {limit} 字,outcome 为 denied 时必填", limit=MAX_READ_REASON))
|
|
332
|
+
return op, root, path, size, outcome, reason
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def read_decision(row, root, size, outcome, reason, usage):
|
|
336
|
+
"""Decide one read: (allowed, code, reason). Only reads the engine served count toward the quota."""
|
|
337
|
+
if row["status"] != "active":
|
|
338
|
+
return False, "member_ended", ENDED_TEXTS.get(row["end_reason"], ENDED_TEXTS["revoked"])
|
|
339
|
+
if outcome == "denied":
|
|
340
|
+
return False, "engine_denied", reason
|
|
341
|
+
if row["scope"] != "read":
|
|
342
|
+
return False, "not_readable", Text("该外部成员只讨论,未开放读取项目")
|
|
343
|
+
if root >= len(json.loads(row["directories"])):
|
|
344
|
+
return False, "bad_root", Text("该目录未对外部成员开放")
|
|
345
|
+
if usage["hour_reads"] + 1 > row["hourly_reads"]:
|
|
346
|
+
return False, "quota_hour_reads", Text("本小时读取次数已达上限")
|
|
347
|
+
if usage["hour_bytes"] + size > row["hourly_bytes"]:
|
|
348
|
+
return False, "quota_hour_bytes", Text("本小时读取量已达上限")
|
|
349
|
+
if usage["total_bytes"] + size > row["total_bytes"]:
|
|
350
|
+
return False, "quota_total_bytes", Text("读取总量已达上限")
|
|
351
|
+
return True, "ok", ""
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def record_read(connection, room_id, member_id, token, payload):
|
|
355
|
+
"""Audit one read, then judge it against the persisted quota, and commit before the gateway may return content.
|
|
356
|
+
|
|
357
|
+
The audit row and the room event are written first (as not allowed), the decision updates them in the same
|
|
358
|
+
transaction, and the transaction commits here: a failure anywhere raises, so the gateway returns nothing.
|
|
359
|
+
"""
|
|
360
|
+
require_owner(connection, room_id, token)
|
|
361
|
+
begin_write(connection)
|
|
362
|
+
op, root, path, size, outcome, reason = checked_read(payload)
|
|
363
|
+
expire_room(connection, room_id)
|
|
364
|
+
row = external_row(connection, room_id, member_id)
|
|
365
|
+
directories = json.loads(row["directories"])
|
|
366
|
+
directory = directories[root] if root < len(directories) else ""
|
|
367
|
+
at = int(time.time() * 1000)
|
|
368
|
+
cursor = connection.execute("""INSERT INTO external_reads (member_id,room_id,at,op,root,directory,path,bytes,allowed,code,reason)
|
|
369
|
+
VALUES (?,?,?,?,?,?,?,?,0,'pending','')""", (member_id, room_id, at, op, root, directory, path, size))
|
|
370
|
+
read_id = cursor.lastrowid
|
|
371
|
+
event = connection.execute("INSERT INTO room_events (room_id,at,kind,data) VALUES (?,?,'external.read',?)",
|
|
372
|
+
(room_id, at, json.dumps({"member_id": member_id, "read_id": read_id}))).lastrowid
|
|
373
|
+
allowed, code, why = read_decision(row, root, size, outcome, reason, usage_of(connection, member_id))
|
|
374
|
+
connection.execute("UPDATE external_reads SET allowed=?,code=?,reason=? WHERE id=?", (int(allowed), code, str(why), read_id))
|
|
375
|
+
data = {"member_id": member_id, "member": row["name"], "read_id": read_id, "op": op, "root": root, "directory": directory,
|
|
376
|
+
"path": path, "bytes": size, "allowed": allowed, "code": code, "reason": str(why)}
|
|
377
|
+
connection.execute("UPDATE room_events SET data=? WHERE id=?", (json.dumps(data, ensure_ascii=False), event))
|
|
378
|
+
connection.commit()
|
|
379
|
+
return {"allowed": allowed, "code": code, "reason": why, "reason_text": text_payload(why), "read_id": read_id, "recorded": True,
|
|
380
|
+
"usage": usage_of(connection, member_id)}
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def require_external(connection, room_id, token):
|
|
384
|
+
"""Resolve the external member of this room from its own credential; an ended one is refused with its reason."""
|
|
385
|
+
begin_write(connection)
|
|
386
|
+
hashed = token_hash(token)
|
|
387
|
+
row = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? AND x.token_hash=?", (room_id, hashed)).fetchone() if hashed else None
|
|
388
|
+
if not row:
|
|
389
|
+
raise classified(PermissionError, Text("需要本房间外部成员的凭证"), "external_credential_required")
|
|
390
|
+
if row["status"] == "active" and row["expires_at"] <= int(time.time()):
|
|
391
|
+
end_member(connection, row, "expired")
|
|
392
|
+
# Kept although the request is refused: the error rolls the request back otherwise.
|
|
393
|
+
connection.commit()
|
|
394
|
+
begin_write(connection)
|
|
395
|
+
row = external_row(connection, room_id, row["id"])
|
|
396
|
+
if row["status"] != "active":
|
|
397
|
+
raise classified(PermissionError, ENDED_TEXTS.get(row["end_reason"], ENDED_TEXTS["revoked"]), "external_ended",
|
|
398
|
+
reason=row["end_reason"] or "revoked")
|
|
399
|
+
return dict(row)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def member_room_view(connection, room_id, member):
|
|
403
|
+
"""What an external member sees of the room: title and goal, the roster by name, its own grant; no paths or credentials."""
|
|
404
|
+
room = connection.execute("SELECT r.id,r.title,r.goal,d.archived FROM rooms r JOIN room_directory d ON d.room_id=r.id WHERE r.id=?",
|
|
405
|
+
(room_id,)).fetchone()
|
|
406
|
+
labels = free_room.member_display_names(connection, room_id)
|
|
407
|
+
members = [{"name": row["name"], "label": labels.get(row["name"], row["name"]), "role": row["role"], "status": row["status"],
|
|
408
|
+
"external": row["access"] == "external"}
|
|
409
|
+
for row in connection.execute("SELECT name,role,status,access FROM room_members WHERE room_id=? AND status<>'removed' ORDER BY id",
|
|
410
|
+
(room_id,))]
|
|
411
|
+
latest = connection.execute("""SELECT COALESCE(MAX(id),0) FROM messages m WHERE room_id=?
|
|
412
|
+
AND NOT EXISTS (SELECT 1 FROM internal_task_messages t WHERE t.message_id=m.id)""", (room_id,)).fetchone()[0]
|
|
413
|
+
me = {"member_id": member["id"], "name": member["name"], "label": labels.get(member["name"], member["name"]), "scope": member["scope"],
|
|
414
|
+
"expires_at": member["expires_at"], "directories": directory_names(json.loads(member["directories"])),
|
|
415
|
+
"quota": quota_of(member), "usage": usage_of(connection, member["id"])}
|
|
416
|
+
return {"room": {"id": room["id"], "title": room["title"], "goal": room["goal"], "archived": bool(room["archived"])},
|
|
417
|
+
"me": me, "members": members, "latest_message_id": latest}
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def member_inbox(connection, room_id, member):
|
|
421
|
+
"""The external member's own open requests, with the same context fields the runner's inbox gives, and its live execution."""
|
|
422
|
+
pending = free_room.pending_requests(connection, member["id"])
|
|
423
|
+
executions = [free_room.public_execution(row) for row in connection.execute(
|
|
424
|
+
"SELECT * FROM member_executions WHERE member_id=? AND status IN ('dispatched','started') ORDER BY id", (member["id"],))]
|
|
425
|
+
return {"member": {"member_id": member["id"], "name": member["name"], "status": member["status"], "expires_at": member["expires_at"]},
|
|
426
|
+
"pending": pending, "executions": executions}
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def decline_requests(connection, room_id, member, payload):
|
|
430
|
+
"""A declines or lets time out its own pending requests; B then shows them as not agreed to."""
|
|
431
|
+
request_ids, outcome = payload.get("request_ids"), payload.get("outcome")
|
|
432
|
+
if outcome not in DECLINE_OUTCOMES:
|
|
433
|
+
raise ValueError(Text("outcome 须为 declined 或 timeout"))
|
|
434
|
+
if (not isinstance(request_ids, list) or not 0 < len(request_ids) <= MAX_DECLINES
|
|
435
|
+
or any(type(item) is not int for item in request_ids) or len(set(request_ids)) != len(request_ids)):
|
|
436
|
+
raise ValueError(Text("request_ids 须为 1–{limit} 个不重复的请求编号", limit=MAX_DECLINES))
|
|
437
|
+
for request_id in request_ids:
|
|
438
|
+
row = connection.execute("SELECT member_id,status FROM member_requests WHERE room_id=? AND id=?", (room_id, request_id)).fetchone()
|
|
439
|
+
if not row or row["member_id"] != member["id"] or row["status"] != "pending":
|
|
440
|
+
raise FileExistsError(Text("请求 {request_id} 不属于本成员或已处理", request_id=request_id))
|
|
441
|
+
now = int(time.time())
|
|
442
|
+
marks = ",".join("?" * len(request_ids))
|
|
443
|
+
for request_id in request_ids:
|
|
444
|
+
connection.execute("INSERT OR REPLACE INTO external_declines (request_id,member_id,outcome,at) VALUES (?,?,?,?)",
|
|
445
|
+
(request_id, member["id"], outcome, now))
|
|
446
|
+
free_room.record_cancel_reasons(connection, f"id IN ({marks})", tuple(request_ids), "no_reply")
|
|
447
|
+
connection.execute(f"UPDATE member_requests SET status='cancelled' WHERE id IN ({marks})", tuple(request_ids))
|
|
448
|
+
free_room.discussion.after_member_stopped(connection, member["id"])
|
|
449
|
+
free_room.settle_batches(connection, room_id)
|
|
450
|
+
return {"declined": request_ids, "outcome": outcome}
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def answer_payload(member, payload):
|
|
454
|
+
"""Keep only what an external answer may carry; the author is always the member itself and an execution is required."""
|
|
455
|
+
extra = set(payload) - set(ANSWER_FIELDS) - {"author"}
|
|
456
|
+
if extra:
|
|
457
|
+
raise ValueError(Text("外部成员的回答不能带这些字段:{fields}", fields="、".join(sorted(extra))))
|
|
458
|
+
if payload.get("author", member["name"]) != member["name"]:
|
|
459
|
+
raise PermissionError(Text("成员只能以本人身份发言"))
|
|
460
|
+
if type(payload.get("execution_id")) is not int:
|
|
461
|
+
raise ValueError(Text("成员回答须关联本次执行编号 execution_id"))
|
|
462
|
+
return {**{key: payload[key] for key in ANSWER_FIELDS if key in payload}, "author": member["name"], "source": "cli"}
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def leave_room(connection, member):
|
|
466
|
+
"""The external member leaves on its own; its credential stops working at once."""
|
|
467
|
+
end_member(connection, member, "left")
|
|
468
|
+
return {"left": True}
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def external_api(connection, parts, params, method, token, read_payload, hooks):
|
|
472
|
+
"""Serve one member-scope route for an external member.
|
|
473
|
+
|
|
474
|
+
Args:
|
|
475
|
+
parts: The split path, starting `api/external/rooms/{room}`.
|
|
476
|
+
read_payload: Callable returning the JSON body of a POST.
|
|
477
|
+
hooks: Server functions this module cannot import: `messages(connection, room_id, params, token)`,
|
|
478
|
+
`message(connection, room_id, message_id, params, token)` and `answer(connection, room_id, payload, member)`.
|
|
479
|
+
|
|
480
|
+
Returns:
|
|
481
|
+
(body, status)
|
|
482
|
+
"""
|
|
483
|
+
room_id, route = parts[3], parts[4:]
|
|
484
|
+
member = require_external(connection, room_id, token)
|
|
485
|
+
reading = {key: params[key] for key in MESSAGE_PARAMS if key in params}
|
|
486
|
+
if method == "GET" and route == ["view"]:
|
|
487
|
+
return member_room_view(connection, room_id, member), 200
|
|
488
|
+
if method == "GET" and route == ["messages"]:
|
|
489
|
+
return hooks["messages"](connection, room_id, reading, token), 200
|
|
490
|
+
if method == "GET" and len(route) == 2 and route[0] == "messages" and route[1].isdigit():
|
|
491
|
+
return hooks["message"](connection, room_id, int(route[1]), reading, token), 200
|
|
492
|
+
if method == "GET" and route == ["inbox"]:
|
|
493
|
+
return member_inbox(connection, room_id, member), 200
|
|
494
|
+
if method != "POST":
|
|
495
|
+
raise LookupError(Text("地址不存在"))
|
|
496
|
+
payload = read_payload()
|
|
497
|
+
if route == ["claim"]:
|
|
498
|
+
return free_room.claim_execution(connection, room_id, member, payload), 200
|
|
499
|
+
if route == ["decline"]:
|
|
500
|
+
return decline_requests(connection, room_id, member, payload), 200
|
|
501
|
+
if len(route) == 2 and route[0] == "executions" and route[1].isdigit():
|
|
502
|
+
if payload.get("action") not in EXECUTION_ACTIONS:
|
|
503
|
+
raise ValueError(Text("外部成员的执行只能 renew、segments、delivery、fail、release 或 quiet"))
|
|
504
|
+
return free_room.execution_action(connection, room_id, int(route[1]), token, payload, member=member), 200
|
|
505
|
+
if route == ["answer"]:
|
|
506
|
+
return hooks["answer"](connection, room_id, answer_payload(member, payload), member), 201
|
|
507
|
+
if route == ["leave"]:
|
|
508
|
+
return leave_room(connection, member), 200
|
|
509
|
+
raise LookupError(Text("地址不存在"))
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def owner_api(connection, room_id, route, params, method, token, read_payload):
|
|
513
|
+
"""Serve the owner's `/api/rooms/{room}/external-members...` routes; returns (body, status)."""
|
|
514
|
+
now = int(time.time())
|
|
515
|
+
if route == [] and method == "GET":
|
|
516
|
+
return list_external(connection, room_id, token), 200
|
|
517
|
+
if route == [] and method == "POST":
|
|
518
|
+
return create_external(connection, room_id, token, read_payload(), now)
|
|
519
|
+
if len(route) >= 1 and route[0].isdigit():
|
|
520
|
+
member_id = int(route[0])
|
|
521
|
+
if route[1:] == [] and method == "GET":
|
|
522
|
+
return get_external(connection, room_id, member_id, token), 200
|
|
523
|
+
if route[1:] == [] and method == "POST":
|
|
524
|
+
return update_external(connection, room_id, member_id, token, read_payload(), now), 200
|
|
525
|
+
if route[1:] == ["reads"] and method == "GET":
|
|
526
|
+
return list_reads(connection, room_id, member_id, token, params), 200
|
|
527
|
+
if route[1:] == ["reads"] and method == "POST":
|
|
528
|
+
return record_read(connection, room_id, member_id, token, read_payload()), 200
|
|
529
|
+
raise LookupError(Text("地址不存在"))
|