This commit is contained in:
Your Name
2026-08-12 11:03:28 +08:00
parent 09d3fcbf82
commit bc9ad1d3cd
32 changed files with 4586 additions and 2341 deletions
@@ -593,6 +593,28 @@ class DemoDoctorRepository:
safe_name = source.name.replace("\\", "_").replace("/", "_")
return f"/demo/uploads/{kind}/{material_id}-{safe_name}"
def upload_material_bytes(
self,
content: bytes,
filename: str,
material_type: Literal["image", "video", "file"],
cid: int = 0,
) -> str:
"""Return a synthetic server URI for an in-memory demo capture."""
if cid < 0:
raise ValueError("cid must be non-negative")
if not content:
raise ValueError("material content must not be empty")
safe_name = Path(filename).name.strip().replace("\\", "_").replace("/", "_")
if not safe_name:
raise ValueError("filename is required")
kind = _material_kind(material_type)
with self._lock:
material_id = self._next_material_id
self._next_material_id += 1
return f"/demo/uploads/{kind}/{material_id}-{safe_name}"
def add_doctor_note(
self,
diagnosis_id: int,
@@ -8,6 +8,7 @@ import time
from collections.abc import Mapping
from contextlib import suppress
from datetime import date
from io import BytesIO
from os import PathLike
from pathlib import Path
from typing import Any, Final, Literal, Protocol
@@ -109,6 +110,15 @@ class DoctorRepository(Protocol):
) -> str:
"""Upload one local note material and return its server URI."""
def upload_material_bytes(
self,
content: bytes,
filename: str,
material_type: Literal["image", "video", "file"],
cid: int = 0,
) -> str:
"""Upload an in-memory capture and return its server URI."""
def get_prescription_template(self, template_id: int) -> PrescriptionTemplate:
"""Return one prescription-library record."""
@@ -960,6 +970,34 @@ class RemoteDoctorRepository:
)
return _normalise_material_reference(payload, endpoint)
def upload_material_bytes(
self,
content: bytes,
filename: str,
material_type: Literal["image", "video", "file"],
cid: int = 0,
) -> str:
"""Upload a trusted in-memory capture without a local plaintext file."""
if cid < 0:
raise ValueError("cid must be non-negative")
if not content:
raise ValueError("material content must not be empty")
if len(content) > 10 * 1024 * 1024:
raise ValueError("material content exceeds 10 MB")
safe_name = Path(filename).name.strip()
if not safe_name or safe_name in {".", ".."}:
raise ValueError("filename is required")
kind = _material_kind(material_type)
mime_type = mimetypes.guess_type(safe_name)[0] or "application/octet-stream"
endpoint = f"upload/{kind}"
payload = self.client.post_multipart(
endpoint,
files={"file": (safe_name, BytesIO(content), mime_type)},
data={"cid": str(cid)},
)
return _normalise_material_reference(payload, endpoint)
def notify_assistant(self, appointment_id: int) -> Any:
"""Ask the server to notify the assigned medical assistant."""
@@ -2,6 +2,9 @@
from __future__ import annotations
import base64
import ctypes
import hashlib
import json
import os
import stat
@@ -28,12 +31,13 @@ _AUTO_KEYRING = object()
class TokenStore:
"""Store access tokens, but never user passwords.
"""Store tokens and optional login passwords with OS-protected storage.
If a working ``keyring`` backend is importable, the token is stored there
and the JSON file contains at most the remembered account name and the
non-secret API scope. Otherwise the JSON file is atomically written with
owner-only ``0600`` permissions.
non-secret API scope. Login passwords use the keyring first; on Windows,
an unavailable keyring falls back to a DPAPI-encrypted blob that only the
current Windows user can decrypt. Plaintext passwords are never written.
"""
def __init__(
@@ -103,7 +107,7 @@ class TokenStore:
"""Persist a token plus optional account and API-scope metadata.
Passing an empty ``account`` explicitly forgets a previously remembered
account. Passwords are never accepted or persisted.
account and its keyring password.
"""
cleaned = token.strip()
@@ -115,6 +119,17 @@ class TokenStore:
data = self._read_file()
if account is not None:
account_value = account.strip()
previous_account = str(data.get("account") or "").strip()
previous_scope = self._normalise_scope(data.get("scope"))
next_scope = (
self._normalise_scope(scope) if scope is not None else previous_scope
)
if previous_account and (
previous_account != account_value
or (account_value and previous_scope != next_scope)
):
self.clear_password(account=previous_account, scope=previous_scope)
data.pop("credential", None)
if account_value:
data["account"] = account_value
else:
@@ -137,7 +152,7 @@ class TokenStore:
self._write_file(data)
def clear_token(self) -> None:
"""Delete the token while retaining an explicitly remembered account."""
"""Delete the token while retaining remembered login credentials."""
if self._uses_keyring and self._keyring is not None:
try:
@@ -146,11 +161,12 @@ class TokenStore:
self._uses_keyring = False
data = self._read_file()
data.pop("token", None)
data.pop("scope", None)
if not data.get("account"):
data.pop("scope", None)
self._write_file(data)
def load_account(self) -> str | None:
"""Load the remembered login account; no password is ever stored."""
"""Load the non-secret remembered login account."""
value = self._read_file().get("account")
return str(value) if isinstance(value, str) and value else None
@@ -167,13 +183,104 @@ class TokenStore:
self._write_file(data)
def clear_account(self) -> None:
"""Forget the remembered account without changing the stored token."""
"""Forget the remembered account and its keyring password."""
data = self._read_file()
self.clear_password(
account=str(data.get("account") or ""),
scope=str(data.get("scope") or ""),
)
self.save_account("")
def load_password(self, *, account: str, scope: str) -> str | None:
"""Load one scoped password from keyring or a Windows DPAPI blob."""
target = self._password_target(account, scope)
if not target:
return None
if self._uses_keyring and self._keyring is not None:
try:
value = self._keyring.get_password(self.service_name, target)
if value:
return str(value)
except Exception:
self._uses_keyring = False
data = self._read_file()
if self._password_target(
str(data.get("account") or ""),
str(data.get("scope") or ""),
) != target:
return None
credential = data.get("credential")
if not isinstance(credential, str) or not credential:
return None
return self._unprotect_password(credential, target)
def save_password(self, password: str, *, account: str, scope: str) -> bool:
"""Save one password using keyring or Windows user-scoped DPAPI."""
target = self._password_target(account, scope)
if not target or not password:
return False
data = self._read_file()
previous_target = self._password_target(
str(data.get("account") or ""),
str(data.get("scope") or ""),
)
if (
previous_target
and previous_target != target
and self._uses_keyring
and self._keyring is not None
):
with suppress(Exception):
self._keyring.delete_password(self.service_name, previous_target)
if self._uses_keyring and self._keyring is not None:
try:
self._keyring.set_password(self.service_name, target, password)
except Exception:
self._uses_keyring = False
else:
data["account"] = account.strip()
data["scope"] = self._normalise_scope(scope)
data.pop("credential", None)
self._write_file(data)
return True
protected = self._protect_password(password, target)
if not protected:
return False
data["account"] = account.strip()
data["scope"] = self._normalise_scope(scope)
data["credential"] = protected
self._write_file(data)
return True
def clear_password(self, *, account: str, scope: str) -> None:
"""Delete one scoped login password from the OS keyring."""
target = self._password_target(account, scope)
if not target:
return
if self._uses_keyring and self._keyring is not None:
with suppress(Exception):
self._keyring.delete_password(self.service_name, target)
data = self._read_file()
stored_target = self._password_target(
str(data.get("account") or ""),
str(data.get("scope") or ""),
)
if stored_target == target and "credential" in data:
data.pop("credential", None)
self._write_file(data)
def clear(self) -> None:
"""Delete both token and remembered account information."""
data = self._read_file()
self.clear_password(
account=str(data.get("account") or ""),
scope=str(data.get("scope") or ""),
)
if self._uses_keyring and self._keyring is not None:
try:
self._keyring.delete_password(self.service_name, self.token_name)
@@ -225,6 +332,120 @@ class TokenStore:
return str(value or "").strip().rstrip("/")
def _password_target(self, account: str, scope: str) -> str:
"""Return an opaque keyring name isolated by account and API server."""
clean_account = account.strip().casefold()
clean_scope = self._normalise_scope(scope).casefold()
if not clean_account or not clean_scope:
return ""
digest = hashlib.sha256(f"{clean_scope}\n{clean_account}".encode()).hexdigest()
return f"login-password:{digest}"
def _protect_password(self, password: str, target: str) -> str | None:
"""Return a Windows DPAPI blob, or ``None`` on unsupported systems."""
if os.name != "nt":
return None
try:
encrypted = self._crypt_protect(
password.encode("utf-8"),
self._credential_entropy(target),
)
except (OSError, ValueError):
return None
return base64.b64encode(encrypted).decode("ascii")
def _unprotect_password(self, protected: str, target: str) -> str | None:
"""Decrypt a Windows DPAPI blob for this account/server target."""
if os.name != "nt":
return None
try:
encrypted = base64.b64decode(protected, validate=True)
plaintext = self._crypt_unprotect(
encrypted,
self._credential_entropy(target),
)
return plaintext.decode("utf-8")
except (OSError, UnicodeError, ValueError):
return None
def _credential_entropy(self, target: str) -> bytes:
return hashlib.sha256(f"{self.service_name}\n{target}".encode()).digest()
@staticmethod
def _crypt_protect(data: bytes, entropy: bytes) -> bytes:
from ctypes import wintypes
class DataBlob(ctypes.Structure):
_fields_ = [
("size", wintypes.DWORD),
("data", ctypes.POINTER(ctypes.c_ubyte)),
]
def make_blob(value: bytes) -> tuple[DataBlob, ctypes.Array[Any]]:
buffer = ctypes.create_string_buffer(value)
blob = DataBlob(
len(value),
ctypes.cast(buffer, ctypes.POINTER(ctypes.c_ubyte)),
)
return blob, buffer
source, _source_buffer = make_blob(data)
optional_entropy, _entropy_buffer = make_blob(entropy)
destination = DataBlob()
if not ctypes.windll.crypt32.CryptProtectData(
ctypes.byref(source),
None,
ctypes.byref(optional_entropy),
None,
None,
0x01,
ctypes.byref(destination),
):
raise ctypes.WinError()
try:
return ctypes.string_at(destination.data, destination.size)
finally:
ctypes.windll.kernel32.LocalFree(destination.data)
@staticmethod
def _crypt_unprotect(data: bytes, entropy: bytes) -> bytes:
from ctypes import wintypes
class DataBlob(ctypes.Structure):
_fields_ = [
("size", wintypes.DWORD),
("data", ctypes.POINTER(ctypes.c_ubyte)),
]
def make_blob(value: bytes) -> tuple[DataBlob, ctypes.Array[Any]]:
buffer = ctypes.create_string_buffer(value)
blob = DataBlob(
len(value),
ctypes.cast(buffer, ctypes.POINTER(ctypes.c_ubyte)),
)
return blob, buffer
source, _source_buffer = make_blob(data)
optional_entropy, _entropy_buffer = make_blob(entropy)
destination = DataBlob()
if not ctypes.windll.crypt32.CryptUnprotectData(
ctypes.byref(source),
None,
ctypes.byref(optional_entropy),
None,
None,
0x01,
ctypes.byref(destination),
):
raise ctypes.WinError()
try:
return ctypes.string_at(destination.data, destination.size)
finally:
ctypes.windll.kernel32.LocalFree(destination.data)
def _read_file(self) -> dict[str, Any]:
try:
content = self.path.read_text(encoding="utf-8")
@@ -234,10 +455,18 @@ class TokenStore:
if not isinstance(value, dict):
return {}
# Explicit allow-list guarantees accidental password-like fields are ignored.
return {key: value[key] for key in ("token", "account", "scope") if key in value}
return {
key: value[key]
for key in ("token", "account", "scope", "credential")
if key in value
}
def _write_file(self, data: dict[str, Any]) -> None:
safe = {key: data[key] for key in ("token", "account", "scope") if data.get(key)}
safe = {
key: data[key]
for key in ("token", "account", "scope", "credential")
if data.get(key)
}
if not safe:
with suppress(OSError):
self.path.unlink(missing_ok=True)