Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 48 additions & 8 deletions backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -565,9 +565,13 @@ def _require_access(
# A proxy-validated cookie can expire or be revoked before this handler.
# Cookie-bearing offline requests must not fall back to anonymous access;
# production service-header priority remains unchanged.
if principal is None and (
getattr(current, "production", False) or getattr(current, "local", False) or session_token is not None
):
# Issue #6: authentication is required in every mode. Test/offline used
# to let requests without any credential through (while rejecting an
# invalid cookie), which exposed protected APIs and other users'
# sessions anonymously. There is intentionally no anonymous fallback
# switch: /api/health and /api/ready stay public for probes, and every
# other caller must present a valid session cookie or service token.
if principal is None:
raise HTTPException(status_code=401, detail="请先登录")
_require_runtime(current)
return principal
Expand All @@ -580,11 +584,19 @@ def _require_service_access(
api_key: str | None = None,
) -> str | None:
_require_secure_transport(current, request)
if not current.production:
return None
principal = _principal_from_headers(current, authorization, api_key)
_require_runtime(current)
return principal
if current.production:
principal = _principal_from_headers(current, authorization, api_key)
_require_runtime(current)
return principal
# Issue #6: the operator endpoint was wide open outside production
# (this function returned before any check). No service API tokens are
# configured in test/offline/local modes, so a logged-in user session is
# the credential here; anonymous access is never allowed. Production
# keeps the stricter service-token-only rule.
username = _username_from_cookie(current, _session_token_from_request(current, request))
if username is None:
raise HTTPException(status_code=401, detail="请先登录")
return f"user:{username}"


def _message_fingerprint(message: str) -> str:
Expand Down Expand Up @@ -1022,6 +1034,34 @@ def create_session(
return SessionCreateResponse(session_id=state["session_id"], state=public_state(state))


@app.get("/api/sessions")
def list_sessions(
http_request: Request,
authorization: str | None = Header(default=None),
api_key: str | None = Header(default=None, alias="X-API-Key"),
) -> dict[str, Any]:
# Registered before /api/sessions/{session_id} so "sessions" is never
# treated as a session id.
current = get_services()
owner_id = _require_access(
current,
http_request,
authorization,
api_key,
_session_token_from_request(current, http_request),
)
try:
sessions = current.store.list_sessions(owner_id)
except SessionBackendError as exc:
raise HTTPException(status_code=503, detail=str(exc)) from exc
return {
"sessions": sessions,
# False when the shared backend cannot enumerate sessions; the list
# is then empty on purpose rather than partial. See store.py.
"complete": current.store.listing_complete,
}


@app.get("/api/sessions/{session_id}")
def get_session(
session_id: str,
Expand Down
6 changes: 6 additions & 0 deletions backend/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class PatientProfile(TypedDict, total=False):
age: int
sex: str
duration: str
temperature: str
symptoms: list[str]
associated_symptoms: list[str]
history: str
Expand All @@ -24,6 +25,11 @@ class WorkflowState(TypedDict, total=False):
owner_id: str
user_message: str
normalized_message: str
# Full turn transcript for this session, oldest first. Each entry is
# plain text plus identifiers only: {"role": "user" | "assistant",
# "content": str, "response_id": str (assistant only), "timestamp": str}.
# No passwords, cookies, or tokens are ever stored here.
messages: list[dict[str, Any]]
profile: PatientProfile
intent: Intent
risk_level: RiskLevel
Expand Down
2 changes: 1 addition & 1 deletion backend/app/safety.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def screen(self, text: str, profile: PatientProfile | None = None) -> RiskAssess
break

if flags:
advice = "建议立即联系当地急救服务或前往最近的急诊;不要仅依赖线上问答等待观察。"
advice = "请立即拨打 120(中国大陆急救电话)或前往最近的急诊;不要仅依赖线上问答等待观察。"
return RiskAssessment("high", tuple(dict.fromkeys(flags)), advice)

watch_flags = [
Expand Down
89 changes: 89 additions & 0 deletions backend/app/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ def create(self, owner_id: str | None = None, idempotency_key: str | None = None
"_version": 0,
"mode": self.mode,
"events": [],
"messages": [],
"citations": [],
"risk_flags": [],
"risk_assessed": False,
Expand Down Expand Up @@ -362,9 +363,97 @@ def request_result(self, session_id: str, request_id: str, owner_id: str | None
result = state.get("request_results", {}).get(request_id)
return merge_request_result(state, result) if isinstance(result, dict) else None

@property
def listing_complete(self) -> bool:
"""Whether :meth:`list_sessions` can enumerate every session.

The in-memory store can. A shared Redis backend cannot be enumerated
(there is no session index), so listing is incomplete by design and
:meth:`list_sessions` returns ``[]`` rather than a partial list.
"""
if self.backend is None:
return True
return callable(getattr(self.backend, "list_states", None))

@staticmethod
def _session_list_entry(state: WorkflowState) -> dict[str, Any]:
messages = state.get("messages", []) or []
first_user = next(
(
str(item.get("content", "")).strip()
for item in messages
if isinstance(item, dict)
and item.get("role") == "user"
and str(item.get("content", "")).strip()
),
"",
)
title = first_user[:30] or str(state.get("summary", "") or "") or "新的健康咨询"
return {
"session_id": state.get("session_id"),
"title": title,
"summary": state.get("summary", ""),
"turn_count": int(state.get("turn_count", 0)),
"updated_at": state.get("updated_at"),
"risk_level": state.get("risk_level") if state.get("risk_assessed") else None,
}

def list_sessions(self, owner_id: str | None = None) -> list[dict[str, Any]]:
"""Return one owner's unexpired sessions, newest first.

Only the in-memory store can enumerate sessions. When a shared
backend is selected and it offers no ``list_states`` enumeration,
this returns ``[]`` (see :attr:`listing_complete`) instead of a
misleading partial list.
"""
owner = str(owner_id or "")
if self.backend is not None:
listing = getattr(self.backend, "list_states", None)
if not callable(listing):
return []
try:
remote_states = listing(owner)
except Exception as exc:
raise SessionBackendError("共享会话后端暂时不可用,请稍后重试") from exc
states = [
state
for state in (remote_states or [])
if isinstance(state, dict) and str(state.get("owner_id", "")) == owner
]
states.sort(key=lambda item: str(item.get("updated_at") or ""), reverse=True)
return [self._session_list_entry(state) for state in states]
with self._lock:
self._purge_expired()
states = [
deepcopy(state)
for state in self._sessions.values()
if str(state.get("owner_id", "")) == owner
]
states.sort(key=lambda item: str(item.get("updated_at") or ""), reverse=True)
return [self._session_list_entry(state) for state in states]

@staticmethod
def _public_messages(state: WorkflowState) -> list[dict[str, Any]]:
"""Return only the transcript fields the API may expose."""
messages: list[dict[str, Any]] = []
for item in state.get("messages", []) or []:
if not isinstance(item, dict) or item.get("role") not in {"user", "assistant"}:
continue
entry: dict[str, Any] = {
"role": item["role"],
"content": str(item.get("content", "")),
}
if item.get("response_id"):
entry["response_id"] = str(item["response_id"])
if item.get("timestamp"):
entry["timestamp"] = str(item["timestamp"])
messages.append(entry)
return messages

def public(self, state: WorkflowState) -> dict:
return {
"session_id": state.get("session_id"),
"messages": self._public_messages(state),
"turn_count": state.get("turn_count", 0),
"profile": state.get("profile", {}),
"risk_level": state.get("risk_level") if state.get("risk_assessed") else None,
Expand Down
Loading