sessionyard 0.7.0__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.
- agent_chat/001_core.sql +172 -0
- agent_chat/002_coordination.sql +63 -0
- agent_chat/003_harness_admission.sql +10 -0
- agent_chat/004_session_titles.sql +3 -0
- agent_chat/005_viewer.sql +9 -0
- agent_chat/006_quotas.sql +6 -0
- agent_chat/007_sender_receipts.sql +20 -0
- agent_chat/008_direct_threads.sql +49 -0
- agent_chat/009_pm_mark.sql +23 -0
- agent_chat/010_quota_backfill.sql +12 -0
- agent_chat/011_roles_and_work.sql +31 -0
- agent_chat/__init__.py +1 -0
- agent_chat/adapter.py +414 -0
- agent_chat/admin.py +524 -0
- agent_chat/api.py +641 -0
- agent_chat/auth.py +226 -0
- agent_chat/browser.py +118 -0
- agent_chat/browser_verify.py +487 -0
- agent_chat/browser_verify_artifacts.py +280 -0
- agent_chat/browser_verify_checks.py +236 -0
- agent_chat/browser_verify_run.py +523 -0
- agent_chat/cli.py +532 -0
- agent_chat/client.py +272 -0
- agent_chat/deliveries.py +555 -0
- agent_chat/events.py +48 -0
- agent_chat/feed.py +193 -0
- agent_chat/http_boundary.py +154 -0
- agent_chat/instance_client.py +349 -0
- agent_chat/instance_file.py +207 -0
- agent_chat/instance_worker.py +326 -0
- agent_chat/mcp/__init__.py +5 -0
- agent_chat/mcp/__main__.py +39 -0
- agent_chat/mcp/app.py +183 -0
- agent_chat/mcp/auth.py +67 -0
- agent_chat/mcp/config.py +55 -0
- agent_chat/mcp/tools.py +295 -0
- agent_chat/metrics.py +60 -0
- agent_chat/models.py +430 -0
- agent_chat/openapi.py +322 -0
- agent_chat/producer.py +208 -0
- agent_chat/protocol.py +71 -0
- agent_chat/publication.py +252 -0
- agent_chat/receipts.py +225 -0
- agent_chat/retention.py +154 -0
- agent_chat/roles.py +153 -0
- agent_chat/rooms.py +179 -0
- agent_chat/sessions.py +340 -0
- agent_chat/skills/agent-chat/SKILL.md +64 -0
- agent_chat/state.py +144 -0
- agent_chat/storage.py +110 -0
- agent_chat/threads.py +50 -0
- agent_chat/web/Manrope-OFL.txt +93 -0
- agent_chat/web/Manrope-Variable.ttf +0 -0
- agent_chat/web/chat.css +936 -0
- agent_chat/web/chat.js +1922 -0
- agent_chat/web/i18n.js +340 -0
- agent_chat/web/index.html +264 -0
- sessionyard-0.7.0.dist-info/METADATA +314 -0
- sessionyard-0.7.0.dist-info/RECORD +62 -0
- sessionyard-0.7.0.dist-info/WHEEL +4 -0
- sessionyard-0.7.0.dist-info/entry_points.txt +3 -0
- sessionyard-0.7.0.dist-info/licenses/LICENSE +661 -0
agent_chat/feed.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Bounded history/event reads under the same clock fence as publication and pruning."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
from uuid import UUID
|
|
7
|
+
|
|
8
|
+
from psycopg import Connection
|
|
9
|
+
|
|
10
|
+
from . import events as event_store
|
|
11
|
+
from . import receipts
|
|
12
|
+
from .auth import authorize_room
|
|
13
|
+
from .models import ROLE_FILTER_STAMPS, Actor, ChatError
|
|
14
|
+
from .rooms import visible
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def message_view(row: dict[str, Any]) -> dict[str, Any]:
|
|
18
|
+
result = dict(row)
|
|
19
|
+
# The stored role is a fact about the sender at publication; it is shown under `sender` only when set.
|
|
20
|
+
role = result.pop("sender_role", None)
|
|
21
|
+
result["sender"] = {
|
|
22
|
+
"principal_id": result.pop("sender_principal_id"),
|
|
23
|
+
"session_id": result.pop("sender_session_id"),
|
|
24
|
+
**{key: result.pop(f"sender_{key}") for key in ("title", "harness", "host", "native_session_id")
|
|
25
|
+
if f"sender_{key}" in result},
|
|
26
|
+
**({} if role is None else {"role": role}),
|
|
27
|
+
}
|
|
28
|
+
return result
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _check_cursor(after: int, clock: dict[str, Any]) -> None:
|
|
32
|
+
if after < clock["retained_floor"]:
|
|
33
|
+
raise ChatError("CURSOR_EXPIRED")
|
|
34
|
+
if after > clock["position"]:
|
|
35
|
+
raise ChatError("INVALID_CURSOR")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
_MESSAGES = """
|
|
39
|
+
SELECT e.position, m.id, m.room_id, m.thread_id, m.reply_to, m.body, m.kind,
|
|
40
|
+
m.sender_principal_id, m.sender_session_id, m.sender_role, m.created_at,
|
|
41
|
+
sender.title AS sender_title, sender.native_session_id AS sender_native_session_id,
|
|
42
|
+
principal.harness AS sender_harness, principal.host AS sender_host,
|
|
43
|
+
t.ref_key AS thread_ref_key, t.resolved_at AS thread_resolved_at,
|
|
44
|
+
ARRAY(SELECT r.session_id FROM agent_chat.recipients r
|
|
45
|
+
WHERE r.message_id = m.id ORDER BY r.session_id) AS recipients
|
|
46
|
+
FROM agent_chat.events e JOIN agent_chat.messages m ON m.id = e.message_id
|
|
47
|
+
JOIN agent_chat.threads t ON t.id = m.thread_id
|
|
48
|
+
LEFT JOIN agent_chat.sessions sender ON sender.id = m.sender_session_id
|
|
49
|
+
JOIN agent_chat.principals principal ON principal.id = m.sender_principal_id
|
|
50
|
+
WHERE e.kind = 'message' AND e.room_id = %s AND e.position > %s AND e.position < %s
|
|
51
|
+
AND m.body IS NOT NULL AND m.expires_at > clock_timestamp()
|
|
52
|
+
AND (%s::uuid IS NULL OR m.thread_id = %s) AND (%s::text IS NULL OR t.ref_key = %s)
|
|
53
|
+
AND (%s::text IS NULL OR m.sender_role = %s)
|
|
54
|
+
"""
|
|
55
|
+
_OLDEST_FIRST = _MESSAGES + " ORDER BY e.position LIMIT %s"
|
|
56
|
+
_NEWEST_FIRST = _MESSAGES + " ORDER BY e.position DESC LIMIT %s"
|
|
57
|
+
_NO_UPPER_BOUND = 9223372036854775807
|
|
58
|
+
EVENT_PAGE = 16
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def history(
|
|
62
|
+
db: Connection[dict[str, Any]],
|
|
63
|
+
actor: Actor,
|
|
64
|
+
room: UUID,
|
|
65
|
+
after: int | None = None,
|
|
66
|
+
limit: int = 100,
|
|
67
|
+
thread: UUID | None = None,
|
|
68
|
+
before: int | None = None,
|
|
69
|
+
ref_key: str | None = None,
|
|
70
|
+
sender_role: str | None = None,
|
|
71
|
+
) -> dict[str, Any]:
|
|
72
|
+
"""Forward pages start at `after` (default: the retained floor). A `before` page holds the newest
|
|
73
|
+
messages below that cursor, in commit order; a cursor above the clock reads the newest page. `sender_role`
|
|
74
|
+
keeps only the messages the service stamped with that role."""
|
|
75
|
+
exclusive = (after is not None and before is not None) or (thread is not None and ref_key is not None)
|
|
76
|
+
if not 1 <= limit <= 100 or exclusive:
|
|
77
|
+
raise ChatError("INVALID_REQUEST")
|
|
78
|
+
stamp = None
|
|
79
|
+
if sender_role is not None:
|
|
80
|
+
stamp = ROLE_FILTER_STAMPS.get(sender_role)
|
|
81
|
+
if stamp is None:
|
|
82
|
+
raise ChatError("INVALID_REQUEST")
|
|
83
|
+
with db.transaction():
|
|
84
|
+
clock = event_store.read_clock(db)
|
|
85
|
+
authorize_room(db, actor, room, read=True)
|
|
86
|
+
start = clock["retained_floor"] if after is None else after
|
|
87
|
+
_check_cursor(start, clock)
|
|
88
|
+
rows = db.execute(
|
|
89
|
+
_OLDEST_FIRST if before is None else _NEWEST_FIRST,
|
|
90
|
+
(
|
|
91
|
+
room, start, _NO_UPPER_BOUND if before is None else before,
|
|
92
|
+
thread, thread, ref_key, ref_key, stamp, stamp, limit + 1,
|
|
93
|
+
),
|
|
94
|
+
).fetchall()
|
|
95
|
+
more = len(rows) > limit
|
|
96
|
+
page = rows[:limit]
|
|
97
|
+
if before is not None:
|
|
98
|
+
page.reverse()
|
|
99
|
+
# A forward page continues after its last row; a `before` page continues before its first, whether or
|
|
100
|
+
# not more rows follow. Only an exhausted forward page names the clock, which reads as "caught up". A
|
|
101
|
+
# `before` page must never answer with the forward head, or a caller paging backwards would re-read the
|
|
102
|
+
# newest page instead of stopping.
|
|
103
|
+
if before is not None:
|
|
104
|
+
next_cursor = page[0]["position"] if page else clock["position"]
|
|
105
|
+
else:
|
|
106
|
+
next_cursor = page[-1]["position"] if more else clock["position"]
|
|
107
|
+
receipt_rows = receipts.snapshots(db, [row["id"] for row in page])
|
|
108
|
+
for row in page:
|
|
109
|
+
row["cursor"] = str(row.pop("position"))
|
|
110
|
+
row["receipts"] = receipt_rows.get(row["id"], [])
|
|
111
|
+
return {
|
|
112
|
+
"messages": [message_view(row) for row in page],
|
|
113
|
+
"next_cursor": str(next_cursor),
|
|
114
|
+
"retained_floor": str(clock["retained_floor"]),
|
|
115
|
+
"position": str(clock["position"]),
|
|
116
|
+
"has_more": more,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def events(
|
|
121
|
+
db: Connection[dict[str, Any]], actor: Actor, after: int, expected_rooms: tuple[UUID, ...] | None = None
|
|
122
|
+
) -> dict[str, Any]:
|
|
123
|
+
with db.transaction():
|
|
124
|
+
clock = event_store.read_clock(db)
|
|
125
|
+
allowed = tuple(sorted(row["id"] for row in visible(db, actor, read=True)))
|
|
126
|
+
if expected_rooms is not None and allowed != expected_rooms:
|
|
127
|
+
# A new room may contain history older than this cursor. Close on additions too.
|
|
128
|
+
raise ChatError("ROOM_SCOPE_CHANGED")
|
|
129
|
+
_check_cursor(after, clock)
|
|
130
|
+
rows = db.execute(
|
|
131
|
+
"""
|
|
132
|
+
SELECT e.position, e.kind AS event_kind, e.room_id AS event_room, e.message_id,
|
|
133
|
+
e.session_id AS event_session,
|
|
134
|
+
CASE WHEN EXISTS (
|
|
135
|
+
SELECT 1 FROM agent_chat.memberships member
|
|
136
|
+
JOIN agent_chat.principal_rooms grant_row ON grant_row.room_id = member.room_id
|
|
137
|
+
JOIN agent_chat.principals principal ON principal.id = grant_row.principal_id
|
|
138
|
+
WHERE member.session_id = s.id AND member.room_id = e.room_id
|
|
139
|
+
AND grant_row.principal_id = s.principal_id AND NOT principal.revoked
|
|
140
|
+
) THEN s.muted END AS current_muted,
|
|
141
|
+
e.state_key AS event_state_key, state.ref_key AS state_ref_key,
|
|
142
|
+
t.ref_key AS thread_ref_key, t.resolved_at AS thread_resolved_at,
|
|
143
|
+
m.id, m.room_id, m.thread_id, m.reply_to, m.kind,
|
|
144
|
+
CASE WHEN m.expires_at > clock_timestamp() THEN m.body ELSE NULL END AS body,
|
|
145
|
+
m.sender_principal_id, m.sender_session_id, m.sender_role, m.created_at,
|
|
146
|
+
sender.title AS sender_title, sender.native_session_id AS sender_native_session_id,
|
|
147
|
+
principal.harness AS sender_harness, principal.host AS sender_host,
|
|
148
|
+
ARRAY(SELECT r.session_id FROM agent_chat.recipients r
|
|
149
|
+
WHERE r.message_id = m.id ORDER BY r.session_id) AS recipients
|
|
150
|
+
FROM agent_chat.events e LEFT JOIN agent_chat.messages m ON m.id = e.message_id
|
|
151
|
+
LEFT JOIN agent_chat.sessions s ON s.id = e.session_id
|
|
152
|
+
LEFT JOIN agent_chat.sessions sender ON sender.id = m.sender_session_id
|
|
153
|
+
LEFT JOIN agent_chat.principals principal ON principal.id = m.sender_principal_id
|
|
154
|
+
LEFT JOIN agent_chat.threads t ON t.id = m.thread_id
|
|
155
|
+
LEFT JOIN agent_chat.room_state state ON state.room_id = e.room_id AND state.state_key = e.state_key
|
|
156
|
+
WHERE e.room_id = ANY(%s::uuid[]) AND e.position > %s ORDER BY e.position LIMIT %s
|
|
157
|
+
""",
|
|
158
|
+
(list(allowed), after, EVENT_PAGE),
|
|
159
|
+
).fetchall()
|
|
160
|
+
receipt_rows = receipts.snapshots(db, [row["message_id"] for row in rows if row["message_id"] is not None])
|
|
161
|
+
result: list[dict[str, Any]] = []
|
|
162
|
+
for row in rows:
|
|
163
|
+
position, kind, room, message_id = (
|
|
164
|
+
row.pop(k) for k in ("position", "event_kind", "event_room", "message_id")
|
|
165
|
+
)
|
|
166
|
+
session, muted = row.pop("event_session"), row.pop("current_muted")
|
|
167
|
+
state_key, state_ref = row.pop("event_state_key"), row.pop("state_ref_key")
|
|
168
|
+
data = {"room_id": room, "message_id": message_id}
|
|
169
|
+
if kind == "state":
|
|
170
|
+
# An invalidation only: the value is read from the state table, never from the replay log. The key
|
|
171
|
+
# may no longer exist (pruned), in which case it has no ref_key to report.
|
|
172
|
+
data = {"room_id": room, "state_key": state_key, "ref_key": state_ref}
|
|
173
|
+
elif kind == "thread":
|
|
174
|
+
data = {"room_id": room, "thread_id": row["thread_id"]}
|
|
175
|
+
elif kind == "message":
|
|
176
|
+
row["receipts"] = receipt_rows.get(message_id, [])
|
|
177
|
+
data["message"] = message_view(row) if row["body"] is not None else None
|
|
178
|
+
elif kind == "receipt":
|
|
179
|
+
data.update(
|
|
180
|
+
session_id=session,
|
|
181
|
+
receipt=next(
|
|
182
|
+
(item for item in receipt_rows.get(message_id, []) if item["session_id"] == session), None
|
|
183
|
+
),
|
|
184
|
+
)
|
|
185
|
+
else:
|
|
186
|
+
data.update(session_id=session, muted=muted)
|
|
187
|
+
result.append({"id": str(position), "event": kind, "data": data})
|
|
188
|
+
# Advancing the in-memory scan over inaccessible rooms is safe; reconnect may
|
|
189
|
+
# repeat that scan. Only actual durable events receive an SSE id on the wire.
|
|
190
|
+
full = len(rows) == EVENT_PAGE
|
|
191
|
+
next_cursor = int(result[-1]["id"]) if full else clock["position"]
|
|
192
|
+
# A full page means the reader is behind: it should read the next page at once.
|
|
193
|
+
return {"events": result, "next_cursor": next_cursor, "rooms": allowed, "full": full}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Bound request bytes before FastAPI parses JSON; never reflect submitted values."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from urllib.parse import parse_qsl
|
|
8
|
+
|
|
9
|
+
from starlette.responses import JSONResponse
|
|
10
|
+
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
|
11
|
+
|
|
12
|
+
SECURITY_HEADERS = {
|
|
13
|
+
"cache-control": "no-store",
|
|
14
|
+
"content-security-policy": (
|
|
15
|
+
"default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; connect-src 'self'; "
|
|
16
|
+
"base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
|
|
17
|
+
),
|
|
18
|
+
"x-content-type-options": "nosniff",
|
|
19
|
+
"referrer-policy": "no-referrer",
|
|
20
|
+
"x-frame-options": "DENY",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
LOG = logging.getLogger("agent_chat.api")
|
|
25
|
+
UNMATCHED = "unmatched"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def log_error(level: int, code: str, route: str, status: int, exc: str, *, mid_stream: bool = False) -> None:
|
|
29
|
+
# The one format for every logged error: a fixed vocabulary of four fields. The route is the matched template
|
|
30
|
+
# or UNMATCHED, so a path value, query, body, header and exception message never reach the journal.
|
|
31
|
+
# A failure after the event stream started has no handler to log it: its status is the 200 already sent,
|
|
32
|
+
# and the extra `phase=stream` marks it.
|
|
33
|
+
suffix = " phase=stream" if mid_stream else ""
|
|
34
|
+
LOG.log(level, "code=%s route=%s status=%d exc=%s" + suffix, code, route, status, exc)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def error_response(code: str, status: int, headers: Mapping[str, str] | None = None) -> JSONResponse:
|
|
38
|
+
return JSONResponse(
|
|
39
|
+
{"error": {"code": code, "message": code}}, status_code=status, headers={**(headers or {}), **SECURITY_HEADERS}
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def refuse(code: str, status: int, scope: Scope, receive: Receive, send: Send) -> None:
|
|
44
|
+
# Refused before routing, so there is no route and no exception object.
|
|
45
|
+
log_error(logging.WARNING, code, UNMATCHED, status, "none")
|
|
46
|
+
await error_response(code, status)(scope, receive, send)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class RequestBoundary:
|
|
50
|
+
def __init__(self, app: ASGIApp, public_origin: str | None = None, metrics=None):
|
|
51
|
+
self.app = app
|
|
52
|
+
self.metrics = metrics
|
|
53
|
+
self.public_origin = public_origin.encode("ascii") if public_origin is not None else None
|
|
54
|
+
|
|
55
|
+
async def _refuse(self, code: str, status: int, scope: Scope, receive: Receive, send: Send) -> None:
|
|
56
|
+
if self.metrics is not None:
|
|
57
|
+
self.metrics.inc(
|
|
58
|
+
"agent_chat_http_errors_total",
|
|
59
|
+
{"route": UNMATCHED, "status": str(status), "code": code},
|
|
60
|
+
)
|
|
61
|
+
await refuse(code, status, scope, receive, send)
|
|
62
|
+
|
|
63
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
64
|
+
if scope["type"] != "http":
|
|
65
|
+
await self.app(scope, receive, send)
|
|
66
|
+
return
|
|
67
|
+
headers = [name.lower() for name, _ in scope["headers"]]
|
|
68
|
+
origins = [value for name, value in scope["headers"] if name.lower() == b"origin"]
|
|
69
|
+
cookie = b"cookie" in headers
|
|
70
|
+
mutation = scope["method"] not in ("GET", "HEAD", "OPTIONS")
|
|
71
|
+
if (
|
|
72
|
+
(origins and (len(origins) != 1 or self.public_origin is None or origins[0] != self.public_origin))
|
|
73
|
+
or (cookie and self.public_origin is None)
|
|
74
|
+
or (mutation and (cookie or scope["path"] == "/v1/login") and origins != [self.public_origin])
|
|
75
|
+
):
|
|
76
|
+
await self._refuse("SESSION_FORBIDDEN", 403, scope, receive, send)
|
|
77
|
+
return
|
|
78
|
+
if cookie and b"authorization" in headers:
|
|
79
|
+
await self._refuse("UNAUTHENTICATED", 401, scope, receive, send)
|
|
80
|
+
return
|
|
81
|
+
if scope["query_string"]:
|
|
82
|
+
allowed = set()
|
|
83
|
+
if scope["method"] == "GET":
|
|
84
|
+
if scope["path"] == "/v1/events":
|
|
85
|
+
allowed = {"after"}
|
|
86
|
+
elif re.fullmatch(r"/v1/rooms/[^/]+/history", scope["path"]):
|
|
87
|
+
allowed = {"after", "before", "limit", "thread_id", "ref_key", "sender_role"}
|
|
88
|
+
elif re.fullmatch(r"/v1/rooms/[^/]+/state", scope["path"]):
|
|
89
|
+
allowed = {"ref_key", "after_key", "limit"}
|
|
90
|
+
elif re.fullmatch(r"/v1/rooms/[^/]+/participants", scope["path"]):
|
|
91
|
+
allowed = {"after_session", "limit", "online"}
|
|
92
|
+
try:
|
|
93
|
+
if len(scope["query_string"]) > 4096:
|
|
94
|
+
raise ValueError
|
|
95
|
+
pairs = parse_qsl(
|
|
96
|
+
scope["query_string"].decode("ascii"),
|
|
97
|
+
keep_blank_values=True,
|
|
98
|
+
strict_parsing=True,
|
|
99
|
+
errors="strict",
|
|
100
|
+
# One field per accepted key, so the cap cannot drift below the allowlist above.
|
|
101
|
+
max_num_fields=max(len(allowed), 1),
|
|
102
|
+
)
|
|
103
|
+
keys = [key for key, _ in pairs]
|
|
104
|
+
if set(keys) - allowed or len(set(keys)) != len(keys):
|
|
105
|
+
raise ValueError
|
|
106
|
+
except (ValueError, UnicodeError):
|
|
107
|
+
await self._refuse("INVALID_REQUEST", 422, scope, receive, send)
|
|
108
|
+
return
|
|
109
|
+
if any(headers.count(name) > 1 for name in (b"authorization", b"cookie", b"last-event-id")):
|
|
110
|
+
await self._refuse("UNAUTHENTICATED", 401, scope, receive, send)
|
|
111
|
+
return
|
|
112
|
+
body = bytearray()
|
|
113
|
+
oversized = False
|
|
114
|
+
try:
|
|
115
|
+
async with asyncio.timeout(5):
|
|
116
|
+
while True:
|
|
117
|
+
message = await receive()
|
|
118
|
+
if message["type"] == "http.disconnect":
|
|
119
|
+
return
|
|
120
|
+
chunk = message.get("body", b"")
|
|
121
|
+
if len(body) + len(chunk) > 131072:
|
|
122
|
+
oversized = True
|
|
123
|
+
break
|
|
124
|
+
body.extend(chunk)
|
|
125
|
+
if not message.get("more_body", False):
|
|
126
|
+
break
|
|
127
|
+
except TimeoutError:
|
|
128
|
+
await self._refuse("REQUEST_TIMEOUT", 408, scope, receive, send)
|
|
129
|
+
return
|
|
130
|
+
if oversized:
|
|
131
|
+
await self._refuse("REQUEST_TOO_LARGE", 413, scope, receive, send)
|
|
132
|
+
return
|
|
133
|
+
if body and scope["method"] in ("GET", "HEAD"):
|
|
134
|
+
await self._refuse("INVALID_REQUEST", 422, scope, receive, send)
|
|
135
|
+
return
|
|
136
|
+
consumed = False
|
|
137
|
+
|
|
138
|
+
async def buffered_receive() -> Message:
|
|
139
|
+
nonlocal consumed
|
|
140
|
+
if not consumed:
|
|
141
|
+
consumed = True
|
|
142
|
+
return {"type": "http.request", "body": bytes(body), "more_body": False}
|
|
143
|
+
return await receive()
|
|
144
|
+
|
|
145
|
+
async def private_send(message: Message) -> None:
|
|
146
|
+
if message["type"] == "http.response.start":
|
|
147
|
+
message["headers"] = [
|
|
148
|
+
(name, value)
|
|
149
|
+
for name, value in message["headers"]
|
|
150
|
+
if name.decode("latin-1").lower() not in SECURITY_HEADERS
|
|
151
|
+
] + [(name.encode("ascii"), value.encode("ascii")) for name, value in SECURITY_HEADERS.items()]
|
|
152
|
+
await send(message)
|
|
153
|
+
|
|
154
|
+
await self.app(scope, buffered_receive, private_send)
|